diff --git a/tests/optimizer/AJSDCE-output.js b/tests/optimizer/AJSDCE-output.js index b4804b9429bf2..4c3fbe3a8c390 100644 --- a/tests/optimizer/AJSDCE-output.js +++ b/tests/optimizer/AJSDCE-output.js @@ -1,15 +1,20 @@ - var z = fleefl(); + var zz = fleefl(); + function g(a) { return a + 1; } + Module["g"] = g; + function h(a) { return a + 1; } + print(h(123)); -((function() { + +(function() { var z = fleefl(); var zz = fleefl(); function g(a) { @@ -20,8 +25,9 @@ print(h(123)); return a + 1; } print(hh(123)); -}))(); +})(); + function glue() { } -glue(); +glue(); diff --git a/tests/optimizer/JSDCE-fors-output.js b/tests/optimizer/JSDCE-fors-output.js new file mode 100644 index 0000000000000..ec992dd36ebbd --- /dev/null +++ b/tests/optimizer/JSDCE-fors-output.js @@ -0,0 +1,3 @@ +for (var i in x) {} + +for (var j = 0; ;) {} diff --git a/tests/optimizer/JSDCE-fors.js b/tests/optimizer/JSDCE-fors.js new file mode 100644 index 0000000000000..71e8010252285 --- /dev/null +++ b/tests/optimizer/JSDCE-fors.js @@ -0,0 +1,4 @@ + +for (var i in x) {} +for (var j = 0;;) {} + diff --git a/tests/optimizer/JSDCE-hasOwnProperty-output.js b/tests/optimizer/JSDCE-hasOwnProperty-output.js index 9916de30819af..187c79613d0f4 100644 --- a/tests/optimizer/JSDCE-hasOwnProperty-output.js +++ b/tests/optimizer/JSDCE-hasOwnProperty-output.js @@ -1,6 +1,7 @@ function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } + if (hasOwnProperty({}, "prop_name")) { console.log("yeah"); } diff --git a/tests/optimizer/JSDCE-output.js b/tests/optimizer/JSDCE-output.js index d650d33c56c2e..042c1583d207f 100644 --- a/tests/optimizer/JSDCE-output.js +++ b/tests/optimizer/JSDCE-output.js @@ -1,19 +1,26 @@ - var z = fleefl(); + var zz = fleefl(); + var keeperObj = { x: fleefl() }; + var keeperArray = [ 1, 2, "3", four() ]; + function g(a) { return a + 1; } + Module["g"] = g; + function h(a) { return a + 1; } + print(h(123)); -((function() { + +(function() { var z = fleefl(); var zz = fleefl(); function g(a) { @@ -24,31 +31,38 @@ print(h(123)); return a + 1; } print(hh(123)); -}))(); +})(); + function glue() { function lookup() { throw 1; } } + glue(); + function _glCreateShader() { return 1; } + function emulate() { _glCreateShader = function _glCreateShader(shaderType) { return glCreateShader(); }; } + emulate(); + ___cxa_find_matching_catch_before(); + function ___cxa_find_matching_catch_before() { if (!___cxa_find_matching_catch_before.buffer) ___cxa_find_matching_catch_before.buffer = {}; } + function ___cxa_find_matching_catch_after() { if (!___cxa_find_matching_catch_after.buffer) ___cxa_find_matching_catch_after.buffer = {}; } -___cxa_find_matching_catch_after(); -var dotOther = Side.effect; - +___cxa_find_matching_catch_after(); +var dotOther = Side.effect; diff --git a/tests/optimizer/JSDCE-uglifyjsNodeTypes-output.js b/tests/optimizer/JSDCE-uglifyjsNodeTypes-output.js deleted file mode 100644 index 1bf7cd9eca866..0000000000000 --- a/tests/optimizer/JSDCE-uglifyjsNodeTypes-output.js +++ /dev/null @@ -1,54 +0,0 @@ -var defun = (function() { -})(); -var name = (function() { -})(); -var object = (function() { -})(); -var non_reserved = (function() { -})(); -function func_1() { -} -function func_2() { -} -function func_3() { -} -function func_4() { -} -function func_5() { -} -function func_6() { -} -function func_7() { -} -function func_8() { -} -function func_9() { -} -function func_10() { -} -var quotedObject = { - "var": func_1, - "defun": func_2, - "function": func_3, - "name": func_4, - "non_reserved": func_5 -}; -var unquotedObject = { - "var": func_6, - defun: func_7, - "function": func_8, - name: func_9, - non_reserved: func_10 -}; -var recursiveObject = { - object: { - func: (function() { - }), - object: { - func: (function() { - }) - } - } -}; -quotedObject || unquotedObject || recursiveObject; - diff --git a/tests/optimizer/JSDCE-uglifyjsNodeTypes.js b/tests/optimizer/JSDCE-uglifyjsNodeTypes.js deleted file mode 100644 index 75af73152df66..0000000000000 --- a/tests/optimizer/JSDCE-uglifyjsNodeTypes.js +++ /dev/null @@ -1,47 +0,0 @@ -var defun = (function () { var a = 1; })(); -var name = (function () { var a = 1; })(); -var object = (function () { var a = 1; })(); -var non_reserved = (function () { var a = 1; })(); - -function func_1() { var a = 1; } -function func_2() { var a = 1; } -function func_3() { var a = 1; } -function func_4() { var a = 1; } -function func_5() { var a = 1; } -function func_6() { var a = 1; } -function func_7() { var a = 1; } -function func_8() { var a = 1; } -function func_9() { var a = 1; } -function func_10() { var a = 1; } -function func_deleted() { var a = 1; } - -var quotedObject = { - "var": func_1, - "defun": func_2, - "function": func_3, - "name": func_4, - "non_reserved": func_5 -}; - -var unquotedObject = { - var: func_6, - defun: func_7, - function: func_8, - name: func_9, - non_reserved: func_10 -}; - -var recursiveObject = { - object: { - func: function () { - var a = 1; - }, - object: { - func: function () { - var b = 1; - } - } - } -}; - -quotedObject || unquotedObject || recursiveObject; // fake uses diff --git a/tests/optimizer/applyDCEGraphRemovals-output.js b/tests/optimizer/applyDCEGraphRemovals-output.js index 3d7641182ae24..a6de0f095ed60 100644 --- a/tests/optimizer/applyDCEGraphRemovals-output.js +++ b/tests/optimizer/applyDCEGraphRemovals-output.js @@ -1,26 +1,40 @@ var name; + var asmLibraryArg = { "save1": 1, "save2": 2 }; + var expD1 = Module["expD1"] = asm["expD1"]; + var expD2 = Module["expD2"] = asm["expD2"]; + var expD3 = Module["expD3"] = asm["expD3"]; -var expD4 = undefined; -var expI1 = Module["expI1"] = (function() { + +var expD4; + +var expI1 = Module["expI1"] = function() { return Module["asm"]["expI1"].apply(null, arguments); -}); -var expI2 = Module["expI2"] = (function() { +}; + +var expI2 = Module["expI2"] = function() { return Module["asm"]["expI2"].apply(null, arguments); -}); -var expI3 = Module["expI3"] = (function() { +}; + +var expI3 = Module["expI3"] = function() { return Module["asm"]["expI3"].apply(null, arguments); -}); -var expI4 = undefined; +}; + +var expI4; + expD1; + Module["expD2"]; + asm["expD3"]; + expI1; + Module["expI2"]; -asm["expI3"]; +asm["expI3"]; diff --git a/tests/optimizer/applyImportAndExportNameChanges-output.js b/tests/optimizer/applyImportAndExportNameChanges-output.js index 10715bec08882..4dcc9fe1c35aa 100644 --- a/tests/optimizer/applyImportAndExportNameChanges-output.js +++ b/tests/optimizer/applyImportAndExportNameChanges-output.js @@ -1,4 +1,5 @@ var name; + var asmLibraryArg = { "a": 1, "A": 33, @@ -12,10 +13,9 @@ var asmLibraryArg = { "d": ___syscall140, "q": ___syscall146 }; -var expD1 = Module["expD1"] = asm["c"]; -var expI1 = Module["expI1"] = (function() { - return Module["asm"]["d"].apply(null, arguments); -}); - +var expD1 = Module["expD1"] = asm["c"]; +var expI1 = Module["expI1"] = function() { + return Module["asm"]["d"].apply(null, arguments); +}; diff --git a/tests/optimizer/applyImportAndExportNameChanges2-output.js b/tests/optimizer/applyImportAndExportNameChanges2-output.js new file mode 100644 index 0000000000000..57eeca8ea4802 --- /dev/null +++ b/tests/optimizer/applyImportAndExportNameChanges2-output.js @@ -0,0 +1,237 @@ +var Module; +if (!Module) Module = "__EMSCRIPTEN_PRIVATE_MODULE_EXPORT_NAME_SUBSTITUTION__"; +var ENVIRONMENT_IS_NODE = typeof process === "object"; +if (ENVIRONMENT_IS_NODE) { + var fs = require("fs"); + Module["wasm"] = fs.readFileSync(__dirname + "/a.wasm"); +} +function out(text) { + console.log(text); +} +function err(text) { + console.error(text); +} +function ready() { + run(); +} +function abort(what) { + throw what; +} +var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : undefined; +function UTF8ArrayToString(u8Array, idx, maxBytesToRead) { + var endIdx = idx + maxBytesToRead; + var endPtr = idx; + while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr; + if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) { + return UTF8Decoder.decode(u8Array.subarray(idx, endPtr)); + } else { + var str = ""; + while (idx < endPtr) { + var u0 = u8Array[idx++]; + if (!(u0 & 128)) { + str += String.fromCharCode(u0); + continue; + } + var u1 = u8Array[idx++] & 63; + if ((u0 & 224) == 192) { + str += String.fromCharCode((u0 & 31) << 6 | u1); + continue; + } + var u2 = u8Array[idx++] & 63; + if ((u0 & 240) == 224) { + u0 = (u0 & 15) << 12 | u1 << 6 | u2; + } else { + u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | u8Array[idx++] & 63; + } + if (u0 < 65536) { + str += String.fromCharCode(u0); + } else { + var ch = u0 - 65536; + str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); + } + } + } + return str; +} +function UTF8ToString(ptr, maxBytesToRead) { + return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ""; +} +var TOTAL_MEMORY = 16777216, STATIC_BASE = 1024, DYNAMICTOP_PTR = 6016; +var wasmMaximumMemory = TOTAL_MEMORY; +var wasmMemory = new WebAssembly.Memory({ + "initial": TOTAL_MEMORY >> 16, + "maximum": wasmMaximumMemory >> 16 +}); +var buffer = wasmMemory.buffer; +var HEAP8 = new Int8Array(buffer); +var HEAP16 = new Int16Array(buffer); +var HEAP32 = new Int32Array(buffer); +var HEAPU8 = new Uint8Array(buffer); +var HEAPU16 = new Uint16Array(buffer); +var HEAPU32 = new Uint32Array(buffer); +var HEAPF32 = new Float32Array(buffer); +var HEAPF64 = new Float64Array(buffer); +HEAP32[DYNAMICTOP_PTR >> 2] = 5249152; +var SYSCALLS = { + buffers: [ null, [], [] ], + printChar: function(stream, curr) { + var buffer = SYSCALLS.buffers[stream]; + if (curr === 0 || curr === 10) { + (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)); + buffer.length = 0; + } else { + buffer.push(curr); + } + }, + varargs: 0, + get: function(varargs) { + SYSCALLS.varargs += 4; + var ret = HEAP32[SYSCALLS.varargs - 4 >> 2]; + return ret; + }, + getStr: function() { + var ret = UTF8ToString(SYSCALLS.get()); + return ret; + }, + get64: function() { + var low = SYSCALLS.get(), high = SYSCALLS.get(); + return low; + }, + getZero: function() { + SYSCALLS.get(); + } +}; +function ___syscall140(which, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.getStreamFromFD(), offset_high = SYSCALLS.get(), offset_low = SYSCALLS.get(), result = SYSCALLS.get(), whence = SYSCALLS.get(); + var offset = offset_low; + FS.llseek(stream, offset, whence); + HEAP32[result >> 2] = stream.position; + if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; + return 0; + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno; + } +} +function ___syscall146(which, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.get(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get(); + var ret = 0; + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAP32[iov + i * 8 >> 2]; + var len = HEAP32[iov + (i * 8 + 4) >> 2]; + for (var j = 0; j < len; j++) { + SYSCALLS.printChar(stream, HEAPU8[ptr + j]); + } + ret += len; + } + return ret; + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno; + } +} +function ___syscall54(which, varargs) { + SYSCALLS.varargs = varargs; + try { + return 0; + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno; + } +} +function ___syscall6(which, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.getStreamFromFD(); + FS.close(stream); + return 0; + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno; + } +} +function _emscripten_get_now() { + abort(); +} +function _emscripten_random() { + return Math.random(); +} +function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.set(HEAPU8.subarray(src, src + num), dest); +} +if (ENVIRONMENT_IS_NODE) { + _emscripten_get_now = function _emscripten_get_now_actual() { + var t = process["hrtime"](); + return t[0] * 1e3 + t[1] / 1e6; + }; +} else if (typeof dateNow !== "undefined") { + _emscripten_get_now = dateNow; +} else if (typeof self === "object" && self["performance"] && typeof self["performance"]["now"] === "function") { + _emscripten_get_now = function() { + return self["performance"]["now"](); + }; +} else if (typeof performance === "object" && typeof performance["now"] === "function") { + _emscripten_get_now = function() { + return performance["now"](); + }; +} else { + _emscripten_get_now = Date.now; +} +var asmLibraryArg = { + "b": abort, + "h": ___syscall140, + "a": ___syscall146, + "g": ___syscall54, + "f": ___syscall6, + "e": _emscripten_get_now, + "d": _emscripten_memcpy_big, + "c": _emscripten_random +}; +function run() { + var ret = _main(); +} +function initRuntime(asm) { + asm["i"](); +} +var env = asmLibraryArg; +env["memory"] = wasmMemory; +env["table"] = new WebAssembly.Table({ + "initial": 6, + "maximum": 6, + "element": "anyfunc" +}); +env["__memory_base"] = STATIC_BASE; +env["__table_base"] = 0; +var imports = { + "env": env, + "global": { + "NaN": NaN, + Infinity: Infinity + }, + "global.Math": Math, + "asm2wasm": { + "f64-rem": function(x, y) { + return x % y; + }, + "debugger": function() { + debugger; + } + } +}; +var ___errno_location, _llvm_bswap_i32, _main, _memcpy, _memset, dynCall_ii, dynCall_iiii; +WebAssembly.instantiate(Module["wasm"], imports).then(function(output) { + var asm = output.instance.exports; + ___errno_location = asm["j"]; + _llvm_bswap_i32 = asm["k"]; + _main = asm["l"]; + _memcpy = asm["m"]; + _memset = asm["n"]; + dynCall_ii = asm["o"]; + dynCall_iiii = asm["p"]; + initRuntime(asm); + ready(); +}); diff --git a/tests/optimizer/applyImportAndExportNameChanges2.js b/tests/optimizer/applyImportAndExportNameChanges2.js new file mode 100644 index 0000000000000..9c1f3ac016034 --- /dev/null +++ b/tests/optimizer/applyImportAndExportNameChanges2.js @@ -0,0 +1,267 @@ +var Module; +if (!Module) Module = "__EMSCRIPTEN_PRIVATE_MODULE_EXPORT_NAME_SUBSTITUTION__"; +var ENVIRONMENT_IS_NODE = typeof process === "object"; +if (ENVIRONMENT_IS_NODE) { + var fs = require("fs"); + Module["wasm"] = fs.readFileSync(__dirname + "/a.wasm") +} + +function out(text) { + console.log(text) +} + +function err(text) { + console.error(text) +} + +function ready() { + run() +} + +function abort(what) { + throw what +} +var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : undefined; + +function UTF8ArrayToString(u8Array, idx, maxBytesToRead) { + var endIdx = idx + maxBytesToRead; + var endPtr = idx; + while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr; + if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) { + return UTF8Decoder.decode(u8Array.subarray(idx, endPtr)) + } else { + var str = ""; + while (idx < endPtr) { + var u0 = u8Array[idx++]; + if (!(u0 & 128)) { + str += String.fromCharCode(u0); + continue + } + var u1 = u8Array[idx++] & 63; + if ((u0 & 224) == 192) { + str += String.fromCharCode((u0 & 31) << 6 | u1); + continue + } + var u2 = u8Array[idx++] & 63; + if ((u0 & 240) == 224) { + u0 = (u0 & 15) << 12 | u1 << 6 | u2 + } else { + u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | u8Array[idx++] & 63 + } + if (u0 < 65536) { + str += String.fromCharCode(u0) + } else { + var ch = u0 - 65536; + str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023) + } + } + } + return str +} + +function UTF8ToString(ptr, maxBytesToRead) { + return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "" +} +var TOTAL_MEMORY = 16777216, + STATIC_BASE = 1024, + DYNAMICTOP_PTR = 6016; +var wasmMaximumMemory = TOTAL_MEMORY; +var wasmMemory = new WebAssembly.Memory({ + "initial": TOTAL_MEMORY >> 16, + "maximum": wasmMaximumMemory >> 16 +}); +var buffer = wasmMemory.buffer; +var HEAP8 = new Int8Array(buffer); +var HEAP16 = new Int16Array(buffer); +var HEAP32 = new Int32Array(buffer); +var HEAPU8 = new Uint8Array(buffer); +var HEAPU16 = new Uint16Array(buffer); +var HEAPU32 = new Uint32Array(buffer); +var HEAPF32 = new Float32Array(buffer); +var HEAPF64 = new Float64Array(buffer); +HEAP32[DYNAMICTOP_PTR >> 2] = 5249152; +var SYSCALLS = { + buffers: [null, [], + [] + ], + printChar: (function(stream, curr) { + var buffer = SYSCALLS.buffers[stream]; + if (curr === 0 || curr === 10) { + (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)); + buffer.length = 0 + } else { + buffer.push(curr) + } + }), + varargs: 0, + get: (function(varargs) { + SYSCALLS.varargs += 4; + var ret = HEAP32[SYSCALLS.varargs - 4 >> 2]; + return ret + }), + getStr: (function() { + var ret = UTF8ToString(SYSCALLS.get()); + return ret + }), + get64: (function() { + var low = SYSCALLS.get(), + high = SYSCALLS.get(); + return low + }), + getZero: (function() { + SYSCALLS.get() + }) +}; + +function ___syscall140(which, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.getStreamFromFD(), + offset_high = SYSCALLS.get(), + offset_low = SYSCALLS.get(), + result = SYSCALLS.get(), + whence = SYSCALLS.get(); + var offset = offset_low; + FS.llseek(stream, offset, whence); + HEAP32[result >> 2] = stream.position; + if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; + return 0 + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno + } +} + +function ___syscall146(which, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.get(), + iov = SYSCALLS.get(), + iovcnt = SYSCALLS.get(); + var ret = 0; + for (var i = 0; i < iovcnt; i++) { + var ptr = HEAP32[iov + i * 8 >> 2]; + var len = HEAP32[iov + (i * 8 + 4) >> 2]; + for (var j = 0; j < len; j++) { + SYSCALLS.printChar(stream, HEAPU8[ptr + j]) + } + ret += len + } + return ret + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno + } +} + +function ___syscall54(which, varargs) { + SYSCALLS.varargs = varargs; + try { + return 0 + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno + } +} + +function ___syscall6(which, varargs) { + SYSCALLS.varargs = varargs; + try { + var stream = SYSCALLS.getStreamFromFD(); + FS.close(stream); + return 0 + } catch (e) { + if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); + return -e.errno + } +} + +function _emscripten_get_now() { + abort() +} + +function _emscripten_random() { + return Math.random() +} + +function _emscripten_memcpy_big(dest, src, num) { + HEAPU8.set(HEAPU8.subarray(src, src + num), dest) +} +if (ENVIRONMENT_IS_NODE) { + _emscripten_get_now = function _emscripten_get_now_actual() { + var t = process["hrtime"](); + return t[0] * 1e3 + t[1] / 1e6 + } +} else if (typeof dateNow !== "undefined") { + _emscripten_get_now = dateNow +} else if (typeof self === "object" && self["performance"] && typeof self["performance"]["now"] === "function") { + _emscripten_get_now = (function() { + return self["performance"]["now"]() + }) +} else if (typeof performance === "object" && typeof performance["now"] === "function") { + _emscripten_get_now = (function() { + return performance["now"]() + }) +} else { + _emscripten_get_now = Date.now +} +var asmLibraryArg = { + "abort": abort, + "___syscall140": ___syscall140, + "___syscall146": ___syscall146, + "___syscall54": ___syscall54, + "___syscall6": ___syscall6, + "_emscripten_get_now": _emscripten_get_now, + "_emscripten_memcpy_big": _emscripten_memcpy_big, + "_emscripten_random": _emscripten_random +}; + +function run() { + var ret = _main() +} + +function initRuntime(asm) { + asm["__GLOBAL__sub_I_test_global_initializer_cpp"]() +} +var env = asmLibraryArg; +env["memory"] = wasmMemory; +env["table"] = new WebAssembly.Table({ + "initial": 6, + "maximum": 6, + "element": "anyfunc" +}); +env["__memory_base"] = STATIC_BASE; +env["__table_base"] = 0; +var imports = { + "env": env, + "global": { + "NaN": NaN, + "Infinity": Infinity + }, + "global.Math": Math, + "asm2wasm": { + "f64-rem": (function(x, y) { + return x % y + }), + "debugger": (function() { + debugger + }) + } +}; +var ___errno_location, _llvm_bswap_i32, _main, _memcpy, _memset, dynCall_ii, dynCall_iiii; +WebAssembly.instantiate(Module["wasm"], imports).then((function(output) { + var asm = output.instance.exports; + ___errno_location = asm["___errno_location"]; + _llvm_bswap_i32 = asm["_llvm_bswap_i32"]; + _main = asm["_main"]; + _memcpy = asm["_memcpy"]; + _memset = asm["_memset"]; + dynCall_ii = asm["dynCall_ii"]; + dynCall_iiii = asm["dynCall_iiii"]; + initRuntime(asm); + ready() +})) + + + +// EXTRA_INFO: {"mapping": {"_llvm_bswap_i32": "k", "_emscripten_random": "c", "dynCall_ii": "o", "__GLOBAL__sub_I_test_global_initializer_cpp": "i", "___errno_location": "j", "dynCall_iiii": "p", "___syscall6": "f", "_memset": "n", "_memcpy": "m", "abort": "b", "___syscall146": "a", "_emscripten_memcpy_big": "d", "___syscall54": "g", "___syscall140": "h", "_emscripten_get_now": "e", "_main": "l"}} diff --git a/tests/test_other.py b/tests/test_other.py index 54dba4ba3e48a..01c976030deb9 100644 --- a/tests/test_other.py +++ b/tests/test_other.py @@ -2106,7 +2106,9 @@ def test_save_bc(self): assert 'hello, world!' in run_js('two.js') def test_js_optimizer(self): + ACORN_PASSES = ['JSDCE', 'AJSDCE', 'applyImportAndExportNameChanges', 'emitDCEGraph', 'applyDCEGraphRemovals'] for input, expected, passes in [ + (path_from_root('tests', 'optimizer', 'eliminateDeadGlobals.js'), open(path_from_root('tests', 'optimizer', 'eliminateDeadGlobals-output.js')).read(), ['eliminateDeadGlobals']), (path_from_root('tests', 'optimizer', 'test-js-optimizer.js'), open(path_from_root('tests', 'optimizer', 'test-js-optimizer-output.js')).read(), @@ -2179,30 +2181,32 @@ def test_js_optimizer(self): ['splitMemory']), (path_from_root('tests', 'optimizer', 'JSDCE.js'), open(path_from_root('tests', 'optimizer', 'JSDCE-output.js')).read(), ['JSDCE']), - (path_from_root('tests', 'optimizer', 'JSDCE-uglifyjsNodeTypes.js'), open(path_from_root('tests', 'optimizer', 'JSDCE-uglifyjsNodeTypes-output.js')).read(), - ['JSDCE']), (path_from_root('tests', 'optimizer', 'JSDCE-hasOwnProperty.js'), open(path_from_root('tests', 'optimizer', 'JSDCE-hasOwnProperty-output.js')).read(), ['JSDCE']), + (path_from_root('tests', 'optimizer', 'JSDCE-fors.js'), open(path_from_root('tests', 'optimizer', 'JSDCE-fors-output.js')).read(), + ['JSDCE']), (path_from_root('tests', 'optimizer', 'AJSDCE.js'), open(path_from_root('tests', 'optimizer', 'AJSDCE-output.js')).read(), ['AJSDCE']), (path_from_root('tests', 'optimizer', 'emitDCEGraph.js'), open(path_from_root('tests', 'optimizer', 'emitDCEGraph-output.js')).read(), - ['emitDCEGraph', 'noEmitAst']), + ['emitDCEGraph', 'noPrint']), (path_from_root('tests', 'optimizer', 'emitDCEGraph2.js'), open(path_from_root('tests', 'optimizer', 'emitDCEGraph2-output.js')).read(), - ['emitDCEGraph', 'noEmitAst']), + ['emitDCEGraph', 'noPrint']), (path_from_root('tests', 'optimizer', 'emitDCEGraph3.js'), open(path_from_root('tests', 'optimizer', 'emitDCEGraph3-output.js')).read(), - ['emitDCEGraph', 'noEmitAst']), + ['emitDCEGraph', 'noPrint']), (path_from_root('tests', 'optimizer', 'emitDCEGraph4.js'), open(path_from_root('tests', 'optimizer', 'emitDCEGraph4-output.js')).read(), - ['emitDCEGraph', 'noEmitAst']), + ['emitDCEGraph', 'noPrint']), (path_from_root('tests', 'optimizer', 'emitDCEGraph5.js'), open(path_from_root('tests', 'optimizer', 'emitDCEGraph5-output.js')).read(), - ['emitDCEGraph', 'noEmitAst']), + ['emitDCEGraph', 'noPrint']), (path_from_root('tests', 'optimizer', 'applyDCEGraphRemovals.js'), open(path_from_root('tests', 'optimizer', 'applyDCEGraphRemovals-output.js')).read(), ['applyDCEGraphRemovals']), (path_from_root('tests', 'optimizer', 'applyImportAndExportNameChanges.js'), open(path_from_root('tests', 'optimizer', 'applyImportAndExportNameChanges-output.js')).read(), ['applyImportAndExportNameChanges']), + (path_from_root('tests', 'optimizer', 'applyImportAndExportNameChanges2.js'), open(path_from_root('tests', 'optimizer', 'applyImportAndExportNameChanges2-output.js')).read(), + ['applyImportAndExportNameChanges']), (path_from_root('tests', 'optimizer', 'detectSign-modulus-emterpretify.js'), open(path_from_root('tests', 'optimizer', 'detectSign-modulus-emterpretify-output.js')).read(), ['noPrintMetadata', 'emterpretify', 'noEmitAst']), (path_from_root('tests', 'optimizer', 'minimal-runtime-emitDCEGraph.js'), open(path_from_root('tests', 'optimizer', 'minimal-runtime-emitDCEGraph-output.js')).read(), - ['emitDCEGraph', 'noEmitAst']), + ['emitDCEGraph', 'noPrint']), ]: print(input, passes) @@ -2210,9 +2214,15 @@ def test_js_optimizer(self): expected = [expected] expected = [out.replace('\n\n', '\n').replace('\n\n', '\n') for out in expected] - # test calling js optimizer - print(' js') - output = run_process(NODE_JS + [path_from_root('tools', 'js-optimizer.js'), input] + passes, stdin=PIPE, stdout=PIPE).stdout + acorn = any([p for p in passes if p in ACORN_PASSES]) + + # test calling optimizer + if not acorn: + print(' js') + output = run_process(NODE_JS + [path_from_root('tools', 'js-optimizer.js'), input] + passes, stdin=PIPE, stdout=PIPE).stdout + else: + print(' acorn') + output = run_process(NODE_JS + [path_from_root('tools', 'acorn-optimizer.js'), input] + passes, stdin=PIPE, stdout=PIPE).stdout def check_js(js, expected): # print >> sys.stderr, 'chak\n==========================\n', js, '\n===========================\n' @@ -2345,11 +2355,10 @@ def test_debuginfo(self): else: self.assertNotIn(' -g ', finalize) else: - opts = '\n'.join([l for l in lines if os.path.sep + 'opt' in l]) if expect_debug: - self.assertNotIn('strip-debug', opts) + self.assertNotIn('strip-debug', err) else: - self.assertIn('strip-debug', opts) + self.assertIn('strip-debug', err) @unittest.skipIf(not scons_path, 'scons not found in PATH') @with_env_modify({'EMSCRIPTEN_ROOT': path_from_root()}) @@ -8345,10 +8354,28 @@ def test_js_optimizer_parse_error(self): } ''') output = run_process([PYTHON, EMCC, 'src.cpp', '-O2'], stdout=PIPE, stderr=PIPE, check=False) - self.assertContained(''' + # wasm backend output doesn't have spaces in the EM_ASM function bodies + self.assertContained((''' var ASM_CONSTS = [function() { var x = !<->5.; }]; ^ -''', output.stderr) +''', ''' +var ASM_CONSTS = [function() {var x = !<->5.;}]; + ^ +'''), output.stderr) + + def test_EM_ASM_ES6(self): + # check we show a proper understandable error for JS parse problems + create_test_file('src.cpp', r''' +#include +int main() { + EM_ASM({ + var x = (a, b) => 5; // valid ES6! + out('hello!'); + }); +} +''') + run_process([PYTHON, EMCC, 'src.cpp', '-O2']) + self.assertContained('hello!', run_js('a.out.js')) def test_check_sourcemapurl(self): if not self.is_wasm(): diff --git a/tools/acorn-optimizer.js b/tools/acorn-optimizer.js new file mode 100644 index 0000000000000..4890f0e9a5ee7 --- /dev/null +++ b/tools/acorn-optimizer.js @@ -0,0 +1,800 @@ +var acorn = require('acorn'); +var terser = require("terser"); +var fs = require('fs'); +var path = require('path'); + +// Setup + +var print = function(x) { + process.stdout.write(x + '\n'); +}; + +var printErr = function(x) { + process.stderr.write(x + '\n'); +}; + +var read = function(x) { + return fs.readFileSync(x).toString(); +} + +// Utilities + +function assert(condition, text) { + if (!condition) throw text + ' : ' + new Error().stack; +} + +function set(args) { + var ret = {}; + for (var i = 0; i < args.length; i++) { + ret[args[i]] = 0; + } + return ret; +} + +// Visits and walks +// (We don't use acorn-walk because it ignores x in 'x = y'.) + +function visitChildren(node, c) { + // emptyOut() and temporary ignoring may mark nodes as empty, + // while they have properties with children we should ignore. + if (node.type === 'EmptyStatement') { + return; + } + function maybeChild(child) { + if (child && typeof child === 'object' && typeof child.type === 'string') { + c(child); + return true; + } + return false; + } + for (var key in node) { + var child = node[key]; + // Check for a child. + if (!maybeChild(child)) { + // Check for an array of children. + if (Array.isArray(child)) { + child.forEach(maybeChild); + } + } + } +} + +// Simple post-order walk, calling properties on an object by node type, +// if the type exists. +function simpleWalk(node, cs) { + visitChildren(node, function(child) { + simpleWalk(child, cs); + }); + if (node.type in cs) { + cs[node.type](node); + } +} + +// Full post-order walk, calling a single function for all types. +function fullWalk(node, c) { + visitChildren(node, function(child) { + fullWalk(child, c); + }); + c(node); +} + +// Recursive post-order walk, calling properties on an object by node type, +// if the type exists, and if so leaving recursion to that function. +function recursiveWalk(node, cs) { +//print('recw1 ' + JSON.stringify(node)); + (function c(node) { + if (!(node.type in cs)) { + visitChildren(node, function(child) { + recursiveWalk(child, cs); + }); + } else { + cs[node.type](node, c); + } + })(node); +} + +// AST Utilities + +function emptyOut(node) { + node.type = 'EmptyStatement'; +} + +function nullify(node) { + node.type = 'Literal'; + node.value = null; + node.raw = 'null'; +} + +function undefinedify(node) { + node.type = 'Literal'; + node.value = undefined; + node.raw = 'undefined'; +} + +function setLiteralValue(item, value) { + item.value = value; + item.raw = "'" + value + "'"; +} + +function isLiteralString(node) { + return node.type === 'Literal' && + (node.raw[0] === '"' || node.raw[0] === "'"); +} + +function dump(node, text) { + if (text) print(text); + print(JSON.stringify(node, null, ' ')); +} + +// Mark inner scopes temporarily as empty statements. Returns +// a special object that must be used to restore them. +function ignoreInnerScopes(node) { + var map = new WeakMap(); + function ignore(node) { + map.set(node, node.type); + node.type = 'EmptyStatement'; + } + simpleWalk(node, { + FunctionDeclaration(node) { + ignore(node); + }, + FunctionExpression(node) { + ignore(node); + }, + ArrowFunctionExpression(node) { + ignore(node); + }, + // TODO: arrow etc. + }); + return map; +} + +// Mark inner scopes temporarily as empty statements. +function restoreInnerScopes(node, map) { + fullWalk(node, function(node) { + if (map.has(node)) { + node.type = map.get(node); + map.delete(node); + restoreInnerScopes(node, map); + } + }); +} + +// If we empty out a var from +// for (var i in x) {} +// for (var j = 0;;) {} +// then it will be invalid. We saved it on the side; +// restore it here. +function restoreForVars(node) { + var restored = 0; + function fix(init) { + if (init && init.type === 'EmptyStatement') { + assert(init.oldDeclarations); + init.type = 'VariableDeclaration'; + init.declarations = init.oldDeclarations; + restored++; + } + } + simpleWalk(node, { + ForStatement(node) { fix(node.init) }, + ForInStatement(node) { fix(node.left) }, + }); + return restored; +} + +function hasSideEffects(node) { + // Conservative analysis. + var map = ignoreInnerScopes(node); + var has = false; + fullWalk(node, function(node) { + switch (node.type) { + // TODO: go through all the ESTree spec + case 'Literal': + case 'Identifier': + case 'UnaryExpression': + case 'BinaryExpresson': + case 'ExpressionStatement': + case 'UpdateOperator': + case 'ConditionalExpression': + case 'FunctionDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + case 'VariableDeclaration': + case 'VariableDeclarator': + case 'ObjectExpression': + case 'Property': + case 'BlockStatement': + case 'ArrayExpression': + case 'EmptyStatement': { + break; // safe + } + case 'MemberExpression': { + // safe if on Math (or other familiar objects, TODO) + if (node.object.type !== 'Identifier' || + node.object.name !== 'Math') { + //console.error('because member on ' + node.object.name); + has = true; + } + break; + } + default: { + has = true; + //console.error('because ' + node.type); + } + } + }); + restoreInnerScopes(node, map); + return has; +} + +// Passes + +// Removes obviously-unused code. Similar to closure compiler in its rules - +// export e.g. by Module['..'] = theThing; , or use it somewhere, otherwise +// it goes away. +// +// Note that this is somewhat conservative, since the ESTree AST does not +// have a simple separation between definitions and uses, e.g. +// Identifier is used both for the x in function foo(x) { +// and for y = x + 1 . That means we need to consider new ES6+ constructs +// as they appear (like ArrowFunctionExpression). Instead, we do a conservative +// analysis here. + +function JSDCE(ast, multipleIterations) { + function iteration() { + var removed = 0; + var scopes = [{}]; // begin with empty toplevel scope + function DUMP() { + printErr('vvvvvvvvvvvvvv'); + for (var i = 0; i < scopes.length; i++) { + printErr(i + ' : ' + JSON.stringify(scopes[i])); + } + printErr('^^^^^^^^^^^^^^'); + } + function ensureData(scope, name) { + if (Object.prototype.hasOwnProperty.call(scope, name)) return scope[name]; + scope[name] = { + def: 0, + use: 0, + param: 0 // true for function params, which cannot be eliminated + }; + return scope[name]; + } + function cleanUp(ast, names) { + recursiveWalk(ast, { + VariableDeclaration(node, c) { + var old = node.declarations; + var removedHere = 0; + node.declarations = node.declarations.filter(function(node) { + var curr = node.id.name + var value = node.init; + var keep = !(curr in names) || (value && hasSideEffects(value)); + if (!keep) removedHere = 1; + return keep; + }); + removed += removedHere; + if (node.declarations.length === 0) { + emptyOut(node); + // If this is in a for, we may need to restore it. + node.oldDeclarations = old; + } + }, + FunctionDeclaration(node, c) { + if (Object.prototype.hasOwnProperty.call(names, node.id.name)) { + removed++; + emptyOut(node); + return; + } + // do not recurse into other scopes + }, + // do not recurse into other scopes + FunctionExpression() {}, + ArrowFunctionExpression() {}, + }); + removed -= restoreForVars(ast); + } + + function handleFunction(node, c, defun) { + // defun names matter - function names (the y in var x = function y() {..}) are just for stack traces. + if (defun) { + ensureData(scopes[scopes.length-1], node.id.name).def = 1; + } + var scope = {}; + node.params.forEach(function(param) { + var name = param.name; + ensureData(scope, name).def = 1; + scope[name].param = 1; + }); + scopes.push(scope); + c(node.body); + // we can ignore self-references, i.e., references to ourselves inside + // ourselves, for named defined (defun) functions + var ownName = defun ? node.id.name : ''; + var scope = scopes.pop(); + var names = {}; + for (var name in scope) { + if (name === ownName) continue; + var data = scope[name]; + if (data.use && !data.def) { + // this is used from a higher scope, propagate the use down + ensureData(scopes[scopes.length-1], name).use = 1; + continue; + } + if (data.def && !data.use && !data.param) { + // this is eliminateable! + names[name] = 0; + } + } + cleanUp(node.body, names); + } + + recursiveWalk(ast, { + VariableDeclarator(node, c) { + var name = node.id.name; + ensureData(scopes[scopes.length-1], name).def = 1; + if (node.init) c(node.init); + }, + ObjectExpression(node, c) { + // ignore the property identifiers + node.properties.forEach(function(node) { + c(node.value); + }); + }, + FunctionDeclaration(node, c) { + handleFunction(node, c, true /* defun */); + }, + FunctionExpression(node, c) { + handleFunction(node, c); + }, + ArrowFunctionExpression(node, c) { + handleFunction(node, c); + }, + Identifier(node, c) { + var name = node.name; + ensureData(scopes[scopes.length-1], name).use = 1; + }, + }); + + // toplevel + var scope = scopes.pop(); + assert(scopes.length === 0); + + var names = {}; + for (var name in scope) { + var data = scope[name]; + if (data.def && !data.use) { + assert(!data.param); // can't be + // this is eliminateable! + names[name] = 0; + } + } + cleanUp(ast, names); + return removed; + } + while (iteration() && multipleIterations) { } +} + +// Aggressive JSDCE - multiple iterations +function AJSDCE(ast) { + JSDCE(ast, /* multipleIterations= */ true); +} + +function isAsmLibraryArgAssign(node) { // var asmLibraryArg = .. + return node.type === 'VariableDeclaration' && + node.declarations.length === 1 && + node.declarations[0].id.name === 'asmLibraryArg' && + node.declarations[0].init && + node.declarations[0].init.type === 'ObjectExpression'; +} + +function getAsmLibraryArgValue(node) { + return node.declarations[0].init; +} + +function isAsmUse(node) { + return node.type === 'MemberExpression' && + ((node.object.type === 'Identifier' && // asm['X'] + node.object.name === 'asm' && + node.property.type === 'Literal') || + (node.object.type === 'MemberExpression' && // Module['asm']['X'] + node.object.object.type === 'Identifier' && + node.object.object.name === 'Module' && + node.object.property.type === 'Literal' && + node.object.property.value === 'asm' && + isLiteralString(node.property))); +} + +function getAsmOrModuleUseName(node) { + return node.property.value; +} + +function isModuleUse(node) { + return node.type === 'MemberExpression' && // Module['X'] + node.object.type === 'Identifier' && + node.object.name === 'Module' && + isLiteralString(node.property); +} + +function isModuleAsmUse(node) { // Module['asm'][..string..] + return node.type === 'MemberExpression' && + node.object.type === 'MemberExpression' && + node.object.object.type === 'Identifier' && + node.object.object.name === 'Module' && + node.object.property.type === 'Literal' && + node.object.property.value === 'asm' && + isLiteralString(node.property); +} + +// Apply import/export name changes (after minifying them) +function applyImportAndExportNameChanges(ast) { + var mapping = extraInfo.mapping; + fullWalk(ast, function(node) { + if (isAsmLibraryArgAssign(node)) { + var assignedObject = getAsmLibraryArgValue(node); + assignedObject.properties.forEach(function(item) { + if (mapping[item.key.value]) { + setLiteralValue(item.key, mapping[item.key.value]); + } + }); + } else if (node.type === 'AssignmentExpression') { + var target = node.left; + var value = node.right; + if (isAsmUse(value)) { + var name = value.property.value; + if (mapping[name]) { + setLiteralValue(value.property, mapping[name]); + } + } + } else if (isModuleAsmUse(node)) { + var prop = node.property; + var name = prop.value; + if (mapping[name]) { + setLiteralValue(prop, mapping[name]); + } + } else if (isAsmUse(node)) { + var prop = node.property; + var name = prop.value; + if (mapping[name]) { + setLiteralValue(prop, mapping[name]); + } + } + }); +} + +// A static dyncall is dynCall('vii', ..), which is actually static even +// though we call dynCall() - we see the string signature statically. +function isStaticDynCall(node) { + return node.type === 'CallExpression' && + node.callee.type === 'Identifier' && + node.callee.name === 'dynCall' && + isLiteralString(node.arguments[0]) +} + +function getStaticDynCallName(node) { + return 'dynCall_' + node.arguments[0].value; +} + +// a dynamic dyncall is one in which all we know is *some* dynCall may +// be called, but not who. This can be either +// dynCall(*not a string*, ..) +// or, to be conservative, +// "dynCall_" +// as that prefix means we may be constructing a dynamic dyncall name +// (dynCall and embind's requireFunction do this internally). +function isDynamicDynCall(node) { + return (node.type === 'CallExpression' && + node.callee.type === 'Identifier' && + node.callee.name === 'dynCall' && + !isLiteralString(node.arguments[0])) || + (isLiteralString(node) && + node.value === 'dynCall_'); +} + +// +// Emit the DCE graph, to help optimize the combined JS+wasm. +// This finds where JS depends on wasm, and where wasm depends +// on JS, and prints that out. +// +// The analysis here is simplified, and not completely general. It +// is enough to optimize the common case of JS library and runtime +// functions involved in loops with wasm, but not more complicated +// things like JS objects and sub-functions. Specifically we +// analyze as follows: +// +// * We consider (1) the toplevel scope, and (2) the scopes of toplevel defined +// functions (defun, not function; i.e., function X() {} where +// X can be called later, and not y = function Z() {} where Z is +// just a name for stack traces). We also consider the wasm, which +// we can see things going to and arriving from. +// * Anything used in a defun creates a link in the DCE graph, either +// to another defun, or the wasm. +// * Anything used in the toplevel scope is rooted, as it is code +// we assume will execute. The exceptions are +// * when we receive something from wasm; those are "free" and +// do not cause rooting. (They will become roots if they are +// exported, the metadce logic will handle that.) +// * when we send something to wasm; sending a defun causes a +// link in the DCE graph. +// * Anything not in the toplevel or not in a toplevel defun is +// considering rooted. We don't optimize those cases. +// +// Special handling: +// +// * dynCall('vii', ..) are dynamic dynCalls, but we analyze them +// statically, to preserve the dynCall_vii etc. method they depend on. +// Truly dynamic dynCalls (not to a string constant) will not work, +// and require the user to export them. +// * Truly dynamic dynCalls are assumed to reach any dynCall_*. +// +// XXX this modifies the input AST. if you want to keep using it, +// that should be fixed. Currently the main use case here does +// not require that. TODO FIXME +// +function emitDCEGraph(ast) { + // First pass: find the wasm imports and exports, and the toplevel + // defuns, and save them on the side, removing them from the AST, + // which makes the second pass simpler. + // + // The imports that wasm receives look like this: + // + // Module.asmLibraryArg = { "abort": abort, "assert": assert, [..] }; + // + // The exports are trickier, as they have a different form whether or not + // async compilation is enabled. It can be either: + // + // var _malloc = Module["_malloc"] = asm["_malloc"]; + // + // or + // + // var _malloc = Module["_malloc"] = (function() { + // return Module["asm"]["_malloc"].apply(null, arguments); + // }); + // + var imports = []; + var defuns = []; + var dynCallNames = []; + var nameToGraphName = {}; + var modulePropertyToGraphName = {}; + var exportNameToGraphName = {}; // identical to asm['..'] nameToGraphName + var foundAsmLibraryArgAssign = false; + var graph = []; + + function saveAsmExport(name, asmName) { + // the asmName is what the wasm provides directly; the outside JS + // name may be slightly different (extra "_" in wasm backend) + var graphName = getGraphName(name, 'export'); + nameToGraphName[name] = graphName; + modulePropertyToGraphName[name] = graphName; + exportNameToGraphName[asmName] = graphName; + if (/^dynCall_/.test(name)) { + dynCallNames.push(graphName); + } + } + + fullWalk(ast, function(node) { + if (isAsmLibraryArgAssign(node)) { + var assignedObject = getAsmLibraryArgValue(node); + assignedObject.properties.forEach(function(item) { + var value = item.value; + assert(value.type === 'Identifier'); + imports.push(value.name); // the name doesn't matter, only the value which is that actual thing we are importing + }); + foundAsmLibraryArgAssign = true; + emptyOut(node); // ignore this in the second pass; this does not root + } else if (node.type === 'VariableDeclaration') { + if (node.declarations.length === 1) { + var item = node.declarations[0]; + var name = item.id.name; + var value = item.init; + if (value && value.type === 'AssignmentExpression') { + var assigned = value.left; + if (isModuleUse(assigned) && getAsmOrModuleUseName(assigned) === name) { + // this is + // var x = Module['x'] = ? + // which looks like a wasm export being received. confirm with the asm use + var found = 0; + var asmName; + fullWalk(value.right, function(node) { + if (isAsmUse(node)) { + found++; + asmName = getAsmOrModuleUseName(node); + } + }); + // in the wasm backend, the asm name may have one fewer "_" prefixed + if (found === 1) { + // this is indeed an export + // the asmName is what the wasm provides directly; the outside JS + // name may be slightly different (extra "_" in wasm backend) + saveAsmExport(name, asmName); + emptyOut(node); // ignore this in the second pass; this does not root + } + } + } + } + } else if (node.type === 'FunctionDeclaration') { + defuns.push(node); + var name = node.id.name; + nameToGraphName[name] = getGraphName(name, 'defun'); + emptyOut(node); // ignore this in the second pass; we scan defuns separately + } + }); + // must find the info we need + assert(foundAsmLibraryArgAssign, 'could not find the assigment to "asmLibraryArg". perhaps --pre-js or --post-js code moved it out of the global scope? (things like that should be done after emcc runs, as they do not need to be run through the optimizer which is the special thing about --pre-js/--post-js code)'); + // Read exports that were declared in extraInfo + if (extraInfo) { + for (var e in extraInfo.exports) { + var exp = extraInfo.exports[e]; + saveAsmExport(exp[0], exp[1]); + } + } + // Second pass: everything used in the toplevel scope is rooted; + // things used in defun scopes create links + function getGraphName(name, what) { + return 'emcc$' + what + '$' + name; + } + var infos = {}; // the graph name of the item => info for it + imports.forEach(function(import_) { + var name = getGraphName(import_, 'import'); + var info = infos[name] = { + name: name, + import: ['env', import_], + reaches: {} + }; + if (nameToGraphName.hasOwnProperty(import_)) { + info.reaches[nameToGraphName[import_]] = 1; + } // otherwise, it's a number, ignore + }); + for (var e in exportNameToGraphName) { + var name = exportNameToGraphName[e]; + infos[name] = { + name: name, + export: e, + reaches: {} + }; + } + // a function that handles a node we visit, in either a defun or + // the toplevel scope (in which case the second param is not provided) + function visitNode(node, defunInfo) { + // TODO: scope awareness here. for now we just assume all uses are + // from the top scope, which might create more uses than needed + var reached; + if (node.type === 'Identifier') { + var name = node.name; + if (nameToGraphName.hasOwnProperty(name)) { + reached = nameToGraphName[name]; + } + } else if (isModuleUse(node)) { + var name = getAsmOrModuleUseName(node); + if (modulePropertyToGraphName.hasOwnProperty(name)) { + reached = modulePropertyToGraphName[name]; + } + } else if (isStaticDynCall(node)) { + reached = getGraphName(getStaticDynCallName(node), 'export'); + } else if (isDynamicDynCall(node)) { + // this can reach *all* dynCall_* targets, we can't narrow it down + reached = dynCallNames; + } else if (isAsmUse(node)) { + // any remaining asm uses are always rooted in any case + var name = getAsmOrModuleUseName(node); + if (exportNameToGraphName.hasOwnProperty(name)) { + infos[exportNameToGraphName[name]].root = true; + } + return; + } + if (reached) { + function addReach(reached) { + if (defunInfo) { + defunInfo.reaches[reached] = 1; // defun reaches it + } else { + infos[reached].root = true; // in global scope, root it + } + } + if (typeof reached === 'string') { + addReach(reached); + } else { + reached.forEach(addReach); + } + } + } + defuns.forEach(function(defun) { + var name = getGraphName(defun.id.name, 'defun'); + var info = infos[name] = { + name: name, + reaches: {} + }; + fullWalk(defun.body, function(node) { + visitNode(node, info); + }); + }); + fullWalk(ast, function(node) { + visitNode(node, null); + }); + // Final work: print out the graph + // sort for determinism + function sortedNamesFromMap(map) { + var names = []; + for (var name in map) { + names.push(name); + } + names.sort(); + return names; + } + sortedNamesFromMap(infos).forEach(function(name) { + var info = infos[name]; + info.reaches = sortedNamesFromMap(info.reaches); + graph.push(info); + }); + print(JSON.stringify(graph, null, ' ')); +} + +// Apply graph removals from running wasm-metadce +function applyDCEGraphRemovals(ast) { + var unused = set(extraInfo.unused); + + fullWalk(ast, function(node) { + if (isAsmLibraryArgAssign(node)) { + var assignedObject = getAsmLibraryArgValue(node); + assignedObject.properties = assignedObject.properties.filter(function(item) { + var name = item.key.value; + var value = item.value; + var full = 'emcc$import$' + name; + return !((full in unused) && !hasSideEffects(value)); + }); + } else if (node.type === 'AssignmentExpression') { + // when we assign to a thing we don't need, we can just remove the assign + var target = node.left; + if (isAsmUse(target) || isModuleUse(target)) { + var name = getAsmOrModuleUseName(target); + var full = 'emcc$export$' + name; + var value = node.right; + if ((full in unused) && + (isAsmUse(value) || !hasSideEffects(value))) { + undefinedify(node); + } + } + } + }); +} + +// Main + +var arguments = process['argv'].slice(2);; +var infile = arguments[0]; +var passes = arguments.slice(1); + +var input = read(infile); +var extraInfoStart = input.lastIndexOf('// EXTRA_INFO:') +var extraInfo = null; +if (extraInfoStart > 0) { + extraInfo = JSON.parse(input.substr(extraInfoStart + 14)); +} +var ast = acorn.parse(input, { ecmaVersion: 6 }); + +var minifyWhitespace = false; +var noPrint = false; + +var registry = { + JSDCE: JSDCE, + AJSDCE: AJSDCE, + applyImportAndExportNameChanges: applyImportAndExportNameChanges, + emitDCEGraph: emitDCEGraph, + applyDCEGraphRemovals: applyDCEGraphRemovals, + minifyWhitespace: function() { minifyWhitespace = true }, + noPrint: function() { noPrint = true }, + dump: function() { dump(ast) }, +}; + +passes.forEach(function(pass) { + registry[pass](ast); +}); + +if (!noPrint) { + var terserAst = terser.AST_Node.from_mozilla_ast(ast); + var output = terserAst.print_to_string({ + beautify: !minifyWhitespace, + indent_level: minifyWhitespace ? 0 : 1, + keep_quoted_props: true, // for closure + }); + print(output); +} + diff --git a/tools/js-optimizer.js b/tools/js-optimizer.js index 8e1773a5c9541..493010afed615 100644 --- a/tools/js-optimizer.js +++ b/tools/js-optimizer.js @@ -7914,121 +7914,6 @@ function eliminateDeadGlobals(ast) { }); } -// Removes obviously-unused code. Similar to closure compiler in its rules - -// export e.g. by Module['..'] = theThing; , or use it somewhere, otherwise -// it goes away. -function JSDCE(ast, multipleIterations) { - function iteration() { - var removed = false; - var scopes = [{}]; // begin with empty toplevel scope - function DUMP() { - printErr('vvvvvvvvvvvvvv'); - for (var i = 0; i < scopes.length; i++) { - printErr(i + ' : ' + JSON.stringify(scopes[i])); - } - printErr('^^^^^^^^^^^^^^'); - } - function ensureData(scope, name) { - if (Object.prototype.hasOwnProperty.call(scope, name)) return scope[name]; - scope[name] = { - def: 0, - use: 0, - param: 0 // true for function params, which cannot be eliminated - }; - return scope[name]; - } - function cleanUp(ast, names) { - traverse(ast, function(node, type) { - if (type === 'defun' && Object.prototype.hasOwnProperty.call(names, node[1])) { - removed = true; - return emptyNode(); - } - if (type === 'defun' || type === 'function') return null; // do not enter other scopes - if (type === 'var') { - node[1] = node[1].filter(function(varItem, j) { - var curr = varItem[0]; - var value = varItem[1]; - var keep = !(curr in names) || (value && hasSideEffects(value)); - if (!keep) removed = true; - return keep; - }); - if (node[1].length === 0) return emptyNode(); - } - }); - return ast; - } - traverse(ast, function(node, type) { - if (type === 'var') { - node[1].forEach(function(varItem, j) { - var name = varItem[0]; - ensureData(scopes[scopes.length-1], name).def = 1; - }); - return; - } - if (type === 'object') { - return; - } - if (type === 'defun' || type === 'function') { - // defun names matter - function names (the y in var x = function y() {..}) are just for stack traces. - if (type === 'defun') ensureData(scopes[scopes.length-1], node[1]).def = 1; - var scope = {}; - node[2].forEach(function(param) { - ensureData(scope, param).def = 1; - scope[param].param = 1; - }); - scopes.push(scope); - return; - } - if (type === 'name') { - ensureData(scopes[scopes.length-1], node[1]).use = 1; - } - }, function(node, type) { - if (type === 'defun' || type === 'function') { - // we can ignore self-references, i.e., references to ourselves inside - // ourselves, for named defined (defun) functions - var ownName = type === 'defun' ? node[1] : ''; - var scope = scopes.pop(); - var names = set(); - for (name in scope) { - if (name === ownName) continue; - var data = scope[name]; - if (data.use && !data.def) { - // this is used from a higher scope, propagate the use down - ensureData(scopes[scopes.length-1], name).use = 1; - continue; - } - if (data.def && !data.use && !data.param) { - // this is eliminateable! - names[name] = 0; - } - } - cleanUp(node[3], names); - } - }); - // toplevel - var scope = scopes.pop(); - assert(scopes.length === 0); - - var names = set(); - for (var name in scope) { - var data = scope[name]; - if (data.def && !data.use) { - assert(!data.param); // can't be - // this is eliminateable! - names[name] = 0; - } - } - cleanUp(ast, names); - return removed; - } - while (iteration() && multipleIterations) { } -} - -// Aggressive JSDCE - multiple iterations -function AJSDCE(ast) { - JSDCE(ast, /* multipleIterations= */ true); -} - function isAsmLibraryArgAssign(node) { return node[0] === 'var' && node[1][0] && node[1][0][0] == 'asmLibraryArg'; } @@ -8086,330 +7971,6 @@ function isDynamicDynCall(node) { (node[0] === 'string' && node[1] === 'dynCall_'); } -// -// Emit the DCE graph, to help optimize the combined JS+wasm. -// This finds where JS depends on wasm, and where wasm depends -// on JS, and prints that out. -// -// The analysis here is simplified, and not completely general. It -// is enough to optimize the common case of JS library and runtime -// functions involved in loops with wasm, but not more complicated -// things like JS objects and sub-functions. Specifically we -// analyze as follows: -// -// * We consider (1) the toplevel scope, and (2) the scopes of toplevel defined -// functions (defun, not function; i.e., function X() {} where -// X can be called later, and not y = function Z() {} where Z is -// just a name for stack traces). We also consider the wasm, which -// we can see things going to and arriving from. -// * Anything used in a defun creates a link in the DCE graph, either -// to another defun, or the wasm. -// * Anything used in the toplevel scope is rooted, as it is code -// we assume will execute. The exceptions are -// * when we receive something from wasm; those are "free" and -// do not cause rooting. (They will become roots if they are -// exported, the metadce logic will handle that.) -// * when we send something to wasm; sending a defun causes a -// link in the DCE graph. -// * Anything not in the toplevel or not in a toplevel defun is -// considering rooted. We don't optimize those cases. -// -// Special handling: -// -// * dynCall('vii', ..) are dynamic dynCalls, but we analyze them -// statically, to preserve the dynCall_vii etc. method they depend on. -// Truly dynamic dynCalls (not to a string constant) will not work, -// and require the user to export them. -// * Truly dynamic dynCalls are assumed to reach any dynCall_*. -// -// XXX this modifies the input AST. if you want to keep using it, -// that should be fixed. Currently the main use case here does -// not require that. TODO FIXME -// -function emitDCEGraph(ast) { - // First pass: find the wasm imports and exports, and the toplevel - // defuns, and save them on the side, removing them from the AST, - // which makes the second pass simpler. - // - // The imports that wasm receives look like this: - // - // var asmLibraryArg = { "abort": abort, "assert": assert, [..] }; - // - // The exports are trickier, as they have a different form whether or not - // async compilation is enabled. It can be either: - // - // var _malloc = Module["_malloc"] = asm["_malloc"]; - // - // or - // - // var _malloc = Module["_malloc"] = (function() { - // return Module["asm"]["_malloc"].apply(null, arguments); - // }); - // - var imports = []; - var defuns = []; - var dynCallNames = []; - var nameToGraphName = {}; - var modulePropertyToGraphName = {}; - var exportNameToGraphName = {}; // identical to asm['..'] nameToGraphName - var foundAsmLibraryArgAssign = false; - var graph = []; - - function saveAsmExport(name, asmName) { - var graphName = getGraphName(name, 'export'); - nameToGraphName[name] = graphName; - modulePropertyToGraphName[name] = graphName; - exportNameToGraphName[asmName] = graphName; - if (/^dynCall_/.test(name) && dynCallNames.indexOf(name) < 0) { - dynCallNames.push(graphName); - } - } - - traverse(ast, function(node, type) { - if (isAsmLibraryArgAssign(node)) { - var items = asmLibraryArgs(node)[1]; - items.forEach(function(item) { - imports.push(item[1][1]); // the name doesn't matter, only the value which is that actual thing we are importing - }); - foundAsmLibraryArgAssign = true; - return emptyNode(); // ignore this in the second pass; this does not root - } else if (type === 'var') { - if (node[1] && node[1].length === 1) { - var item = node[1][0]; - var name = item[0]; - var value = item[1]; - if (Array.isArray(value) && value[0] === 'assign') { - var assigned = value[2]; - if (isModuleUse(assigned) && getModuleUseName(assigned) === name) { - // this is - // var x = Module['x'] = ? - // which looks like a wasm export being received. confirm with the asm use - var found = 0; - var asmName; - traverse(value[3], function(node, type) { - if (isAsmUse(node)) { - found++; - asmName = getAsmUseName(node); - } - }); - // in the wasm backend, the asm name may have one fewer "_" prefixed - if (found === 1) { - // this is indeed an export - // the asmName is what the wasm provides directly; the outside JS - // name may be slightly different (extra "_" in wasm backend) - saveAsmExport(name, asmName); - return emptyNode(); // ignore this in the second pass; this does not root - } - } - } - } - } else if (type === 'defun') { - defuns.push(node); - var name = node[1]; - nameToGraphName[name] = getGraphName(name, 'defun'); - return emptyNode(); // ignore this in the second pass; we scan defuns separately - } else if (type === 'function') { - return null; // don't look inside - } - }); - // must find the info we need - assert(foundAsmLibraryArgAssign, 'could not find the assigment to "asmLibraryArg". perhaps --pre-js or --post-js code moved it out of the global scope? (things like that should be done after emcc runs, as they do not need to be run through the optimizer which is the special thing about --pre-js/--post-js code)'); - - // Read exports that were declared in extraInfo: - if (extraInfo) { - for(var e in extraInfo.exports) { - var exp = extraInfo.exports[e]; - saveAsmExport(exp[0], exp[1]); - } - } - - // Second pass: everything used in the toplevel scope is rooted; - // things used in defun scopes create links - function getGraphName(name, what) { - return 'emcc$' + what + '$' + name; - } - var infos = {}; // the graph name of the item => info for it - imports.forEach(function(import_) { - var name = getGraphName(import_, 'import'); - var info = infos[name] = { - name: name, - import: ['env', import_], - reaches: {} - }; - if (nameToGraphName.hasOwnProperty(import_)) { - info.reaches[nameToGraphName[import_]] = 1; - } // otherwise, it's a number, ignore - }); - for (var e in exportNameToGraphName) { - var name = exportNameToGraphName[e]; - infos[name] = { - name: name, - export: e, - reaches: {} - }; - } - // a function that handles a node we visit, in either a defun or - // the toplevel scope (in which case the second param is not provided) - function visitNode(node, defunInfo) { - // TODO: scope awareness here. for now we just assume all uses are - // from the top scope, which might create more uses than needed - var reached; - if (node[0] === 'name') { - var name = node[1]; - if (nameToGraphName.hasOwnProperty(name)) { - reached = nameToGraphName[name]; - } - } else if (isModuleUse(node)) { - var name = getModuleUseName(node); - if (modulePropertyToGraphName.hasOwnProperty(name)) { - reached = modulePropertyToGraphName[name]; - } - } else if (isStaticDynCall(node)) { - reached = getGraphName(getStaticDynCallName(node), 'export'); - } else if (isDynamicDynCall(node)) { - // this can reach *all* dynCall_* targets, we can't narrow it down - reached = dynCallNames; - } else if (isAsmUse(node)) { - // any remaining asm uses are always rooted in any case - var name = getAsmUseName(node); - if (exportNameToGraphName.hasOwnProperty(name)) { - infos[exportNameToGraphName[name]].root = true; - } - return; - } - if (reached) { - function addReach(reached) { - if (defunInfo) { - defunInfo.reaches[reached] = 1; // defun reaches it - } else { - infos[reached].root = true; // in global scope, root it - } - } - if (typeof reached === 'string') { - addReach(reached); - } else { - reached.forEach(addReach); - } - } - } - defuns.forEach(function(defun) { - var name = getGraphName(defun[1], 'defun'); - var info = infos[name] = { - name: name, - reaches: {} - }; - traverse(defun[3], function(node, type) { - visitNode(node, info); - }); - }); - traverse(ast, function(node, type) { - visitNode(node, null); - }); - // Final work: print out the graph - // sort for determinism - function sortedNamesFromMap(map) { - var names = []; - for (var name in map) { - names.push(name); - } - names.sort(); - return names; - } - sortedNamesFromMap(infos).forEach(function(name) { - var info = infos[name]; - info.reaches = sortedNamesFromMap(info.reaches); - graph.push(info); - }); - print(JSON.stringify(graph, null, ' ')); -} - -// Apply graph removals from running wasm-metadce -function applyDCEGraphRemovals(ast) { - var unused = set(extraInfo.unused); - - traverse(ast, function(node, type) { - if (isAsmLibraryArgAssign(node)) { - var args = asmLibraryArgs(node); - args[1] = args[1].filter(function(item) { - var name = item[0]; - var value = item[1]; - var full = 'emcc$import$' + name; - return !((full in unused) && !hasSideEffects(value)); - }); - } else if (type === 'assign') { - // when we assign to a thing we don't need, we can just remove the assign - var target = node[2]; - if (isAsmUse(target) || isModuleUse(target)) { - var name = target[2][1]; - var full = 'emcc$export$' + name; - var value = node[3]; - if ((full in unused) && !hasSideEffects(value)) { - return ['name', 'undefined']; - } - } - } - }); -} - -// Apply import/export name changes (after minifying them) -function applyImportAndExportNameChanges(ast) { - var mapping = extraInfo.mapping; - traverse(ast, function(node, type) { - if (isAsmLibraryArgAssign(node)) { - var args = asmLibraryArgs(node); - args[1] = args[1].map(function(item) { - var name = item[0]; - var value = item[1]; - if (mapping[name]) { - var ret = [mapping[name], value]; - // Uglify uses this property to tell it to emit - // { "quotedname": .. } - // as opposed to - // { quotedname: } - // We need quoting for closure compiler to work - // TODO: disable otherwise - ret.quoted = true; - return ret; - } - return item; - }); - } else if (type === 'var') { // var foo = asm["foo"]; - var children = node[1]; - var target = children[0][0]; - var value = children[0][1]; - if (value && isAsmUse(value)) { - var name = value[2][1]; - if (mapping[name]) { - value[2][1] = mapping[name]; - } - } - } else if (type === 'assign') { // foo = asm["foo"]; - var target = node[2]; - var value = node[3]; - if (isAsmUse(value)) { - var name = value[2][1]; - if (mapping[name]) { - value[2][1] = mapping[name]; - } - } - } else if (type === 'call') { // asm["foo"](); - var target = node[1]; - if (isAsmUse(target)) { - var name = target[2][1]; - if (mapping[name]) { - target[2][1] = mapping[name]; - } - } - } else if (isModuleAsmUse(node)) { // Module["asm"]["foo"] - var prop = node[2]; - var name = prop[1]; - if (mapping[name]) { - prop[1] = mapping[name]; - } - } - }); -} - function removeFuncs(ast) { assert(ast[0] === 'toplevel'); var keep = set(extraInfo.keep); @@ -8457,11 +8018,6 @@ var passes = { findReachable: findReachable, dumpCallGraph: dumpCallGraph, asmLastOpts: asmLastOpts, - JSDCE: JSDCE, - AJSDCE: AJSDCE, - emitDCEGraph: emitDCEGraph, - applyDCEGraphRemovals: applyDCEGraphRemovals, - applyImportAndExportNameChanges: applyImportAndExportNameChanges, removeFuncs: removeFuncs, noop: function() {}, diff --git a/tools/js_optimizer.py b/tools/js_optimizer.py index 1a15bf6e2a69f..544ce9033d8ac 100644 --- a/tools/js_optimizer.py +++ b/tools/js_optimizer.py @@ -499,12 +499,11 @@ def write_chunk(chunk, i): temp_files.note(cld) elif cleanup: if DEBUG: print('running cleanup on shell code', file=sys.stderr) - next = cld + '.cl.js' - temp_files.note(next) - proc = subprocess.Popen(js_engine + [JS_OPTIMIZER, cld, 'noPrintMetadata', 'JSDCE'] + (['minifyWhitespace'] if 'minifyWhitespace' in passes else []), stdout=open(next, 'w')) - proc.communicate() - assert proc.returncode == 0 - cld = next + passes = ['JSDCE'] + if 'minifyWhitespace' in passes: + passes.append('minifyWhitespace') + cld = shared.Building.acorn_optimizer(cld, passes) + temp_files.note(cld) coutput = open(cld).read() coutput = coutput.replace('wakaUnknownBefore();', start_asm) diff --git a/tools/node_modules/acorn/CHANGELOG.md b/tools/node_modules/acorn/CHANGELOG.md new file mode 100644 index 0000000000000..a9a08fc0cb519 --- /dev/null +++ b/tools/node_modules/acorn/CHANGELOG.md @@ -0,0 +1,462 @@ +## 6.0.5 (2019-01-02) + +### Bug fixes + +Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. + +Don't treat `let` as a keyword when the next token is `{` on the next line. + +Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. + +## 6.0.4 (2018-11-05) + +### Bug fixes + +Further improvements to tokenizing regular expressions in corner cases. + +## 6.0.3 (2018-11-04) + +### Bug fixes + +Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. + +Remove stray symlink in the package tarball. + +## 6.0.2 (2018-09-26) + +### Bug fixes + +Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix wrong value in `version` export. + +## 6.0.0 (2018-09-14) + +### Bug fixes + +Better handle variable-redefinition checks for catch bindings and functions directly under if statements. + +Forbid `new.target` in top-level arrow functions. + +Fix issue with parsing a regexp after `yield` in some contexts. + +### New features + +The package now comes with TypeScript definitions. + +### Breaking changes + +The default value of the `ecmaVersion` option is now 9 (2018). + +Plugins work differently, and will have to be rewritten to work with this version. + +The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). + +## 5.7.3 (2018-09-10) + +### Bug fixes + +Fix failure to tokenize regexps after expressions like `x.of`. + +Better error message for unterminated template literals. + +## 5.7.2 (2018-08-24) + +### Bug fixes + +Properly handle `allowAwaitOutsideFunction` in for statements. + +Treat function declarations at the top level of modules like let bindings. + +Don't allow async function declarations as the only statement under a label. + +## 5.7.0 (2018-06-15) + +### New features + +Upgraded to Unicode 11. + +## 5.6.0 (2018-05-31) + +### New features + +Allow U+2028 and U+2029 in string when ECMAVersion >= 10. + +Allow binding-less catch statements when ECMAVersion >= 10. + +Add `allowAwaitOutsideFunction` option for parsing top-level `await`. + +## 5.5.3 (2018-03-08) + +### Bug fixes + +A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. + +## 5.5.2 (2018-03-08) + +### Bug fixes + +A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix misleading error message for octal escapes in template strings. + +## 5.5.0 (2018-02-27) + +### New features + +The identifier character categorization is now based on Unicode version 10. + +Acorn will now validate the content of regular expressions, including new ES9 features. + +## 5.4.0 (2018-02-01) + +### Bug fixes + +Disallow duplicate or escaped flags on regular expressions. + +Disallow octal escapes in strings in strict mode. + +### New features + +Add support for async iteration. + +Add support for object spread and rest. + +## 5.3.0 (2017-12-28) + +### Bug fixes + +Fix parsing of floating point literals with leading zeroes in loose mode. + +Allow duplicate property names in object patterns. + +Don't allow static class methods named `prototype`. + +Disallow async functions directly under `if` or `else`. + +Parse right-hand-side of `for`/`of` as an assignment expression. + +Stricter parsing of `for`/`in`. + +Don't allow unicode escapes in contextual keywords. + +### New features + +Parsing class members was factored into smaller methods to allow plugins to hook into it. + +## 5.2.1 (2017-10-30) + +### Bug fixes + +Fix a token context corruption bug. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +Fix token context tracking for `class` and `function` in property-name position. + +Make sure `%*` isn't parsed as a valid operator. + +Allow shorthand properties `get` and `set` to be followed by default values. + +Disallow `super` when not in callee or object position. + +### New features + +Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. + +## 5.1.2 (2017-09-04) + +### Bug fixes + +Disable parsing of legacy HTML-style comments in modules. + +Fix parsing of async methods whose names are keywords. + +## 5.1.1 (2017-07-06) + +### Bug fixes + +Fix problem with disambiguating regexp and division after a class. + +## 5.1.0 (2017-07-05) + +### Bug fixes + +Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. + +Parse zero-prefixed numbers with non-octal digits as decimal. + +Allow object/array patterns in rest parameters. + +Don't error when `yield` is used as a property name. + +Allow `async` as a shorthand object property. + +### New features + +Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. + +## 5.0.3 (2017-04-01) + +### Bug fixes + +Fix spurious duplicate variable definition errors for named functions. + +## 5.0.2 (2017-03-30) + +### Bug fixes + +A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. + +## 5.0.0 (2017-03-28) + +### Bug fixes + +Raise an error for duplicated lexical bindings. + +Fix spurious error when an assignement expression occurred after a spread expression. + +Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. + +Allow labels in front or `var` declarations, even in strict mode. + +### Breaking changes + +Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. + +## 4.0.11 (2017-02-07) + +### Bug fixes + +Allow all forms of member expressions to be parenthesized as lvalue. + +## 4.0.10 (2017-02-07) + +### Bug fixes + +Don't expect semicolons after default-exported functions or classes, even when they are expressions. + +Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. + +## 4.0.9 (2017-02-06) + +### Bug fixes + +Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. + +## 4.0.8 (2017-02-03) + +### Bug fixes + +Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. + +## 4.0.7 (2017-02-02) + +### Bug fixes + +Accept invalidly rejected code like `(x).y = 2` again. + +Don't raise an error when a function _inside_ strict code has a non-simple parameter list. + +## 4.0.6 (2017-02-02) + +### Bug fixes + +Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. + +## 4.0.5 (2017-02-02) + +### Bug fixes + +Disallow parenthesized pattern expressions. + +Allow keywords as export names. + +Don't allow the `async` keyword to be parenthesized. + +Properly raise an error when a keyword contains a character escape. + +Allow `"use strict"` to appear after other string literal expressions. + +Disallow labeled declarations. + +## 4.0.4 (2016-12-19) + +### Bug fixes + +Fix crash when `export` was followed by a keyword that can't be +exported. + +## 4.0.3 (2016-08-16) + +### Bug fixes + +Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. + +Properly parse properties named `async` in ES2017 mode. + +Fix bug where reserved words were broken in ES2017 mode. + +## 4.0.2 (2016-08-11) + +### Bug fixes + +Don't ignore period or 'e' characters after octal numbers. + +Fix broken parsing for call expressions in default parameter values of arrow functions. + +## 4.0.1 (2016-08-08) + +### Bug fixes + +Fix false positives in duplicated export name errors. + +## 4.0.0 (2016-08-07) + +### Breaking changes + +The default `ecmaVersion` option value is now 7. + +A number of internal method signatures changed, so plugins might need to be updated. + +### Bug fixes + +The parser now raises errors on duplicated export names. + +`arguments` and `eval` can now be used in shorthand properties. + +Duplicate parameter names in non-simple argument lists now always produce an error. + +### New features + +The `ecmaVersion` option now also accepts year-style version numbers +(2015, etc). + +Support for `async`/`await` syntax when `ecmaVersion` is >= 8. + +Support for trailing commas in call expressions when `ecmaVersion` is >= 8. + +## 3.3.0 (2016-07-25) + +### Bug fixes + +Fix bug in tokenizing of regexp operator after a function declaration. + +Fix parser crash when parsing an array pattern with a hole. + +### New features + +Implement check against complex argument lists in functions that enable strict mode in ES7. + +## 3.2.0 (2016-06-07) + +### Bug fixes + +Improve handling of lack of unicode regexp support in host +environment. + +Properly reject shorthand properties whose name is a keyword. + +### New features + +Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. + +## 3.1.0 (2016-04-18) + +### Bug fixes + +Properly tokenize the division operator directly after a function expression. + +Allow trailing comma in destructuring arrays. + +## 3.0.4 (2016-02-25) + +### Fixes + +Allow update expressions as left-hand-side of the ES7 exponential operator. + +## 3.0.2 (2016-02-10) + +### Fixes + +Fix bug that accidentally made `undefined` a reserved word when parsing ES7. + +## 3.0.0 (2016-02-10) + +### Breaking changes + +The default value of the `ecmaVersion` option is now 6 (used to be 5). + +Support for comprehension syntax (which was dropped from the draft spec) has been removed. + +### Fixes + +`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. + +A parenthesized class or function expression after `export default` is now parsed correctly. + +### New features + +When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). + +The identifier character ranges are now based on Unicode 8.0.0. + +Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. + +## 2.7.0 (2016-01-04) + +### Fixes + +Stop allowing rest parameters in setters. + +Disallow `y` rexexp flag in ES5. + +Disallow `\00` and `\000` escapes in strict mode. + +Raise an error when an import name is a reserved word. + +## 2.6.2 (2015-11-10) + +### Fixes + +Don't crash when no options object is passed. + +## 2.6.0 (2015-11-09) + +### Fixes + +Add `await` as a reserved word in module sources. + +Disallow `yield` in a parameter default value for a generator. + +Forbid using a comma after a rest pattern in an array destructuring. + +### New features + +Support parsing stdin in command-line tool. + +## 2.5.0 (2015-10-27) + +### Fixes + +Fix tokenizer support in the command-line tool. + +Stop allowing `new.target` outside of functions. + +Remove legacy `guard` and `guardedHandler` properties from try nodes. + +Stop allowing multiple `__proto__` properties on an object literal in strict mode. + +Don't allow rest parameters to be non-identifier patterns. + +Check for duplicate paramter names in arrow functions. diff --git a/tools/node_modules/acorn/LICENSE b/tools/node_modules/acorn/LICENSE new file mode 100644 index 0000000000000..2c0632b6a7c63 --- /dev/null +++ b/tools/node_modules/acorn/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2018 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/node_modules/acorn/README.md b/tools/node_modules/acorn/README.md new file mode 100644 index 0000000000000..a30b20f9c4277 --- /dev/null +++ b/tools/node_modules/acorn/README.md @@ -0,0 +1,274 @@ +# Acorn + +A tiny, fast JavaScript parser written in JavaScript. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). For questions +and discussion, please use the +[Tern discussion forum](https://discuss.ternjs.net). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +**parse**`(input, options)` is the main interface to the library. The +`input` parameter is a string, `options` can be undefined or an object +setting some of the options listed below. The return value will be an +abstract syntax tree object as specified by the [ESTree +spec](https://github.com/estree/estree). + +```javascript +let acorn = require("acorn"); +console.log(acorn.parse("1 + 1")); +``` + +When encountering a syntax error, the parser will raise a +`SyntaxError` object with a meaningful message. The error object will +have a `pos` property that indicates the string offset at which the +error occurred, and a `loc` object that contains a `{line, column}` +object referring to that same position. + +Options can be provided by passing a second argument, which should be +an object containing any of these fields: + +- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be + either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018) or 10 (2019, partial + support). This influences support for strict mode, the set of + reserved words, and support for new syntax features. Default is 7. + + **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being + implemented by Acorn. Other proposed new features can be implemented + through plugins. + +- **sourceType**: Indicate the mode the code should be parsed in. Can be + either `"script"` or `"module"`. This influences global strict mode + and parsing of `import` and `export` declarations. + +- **onInsertedSemicolon**: If given a callback, that callback will be + called whenever a missing semicolon is inserted by the parser. The + callback will be given the character offset of the point where the + semicolon is inserted as argument, and if `locations` is on, also a + `{line, column}` object representing this position. + +- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing + commas. + +- **allowReserved**: If `false`, using a reserved word will generate + an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher + versions. When given the value `"never"`, reserved words and + keywords can also not be used as property names (as in Internet + Explorer's old parser). + +- **allowReturnOutsideFunction**: By default, a return statement at + the top level raises an error. Set this to `true` to accept such + code. + +- **allowImportExportEverywhere**: By default, `import` and `export` + declarations can only appear at a program's top level. Setting this + option to `true` allows them anywhere where a statement is allowed. + +- **allowAwaitOutsideFunction**: By default, `await` expressions can + only appear inside `async` functions. Setting this option to + `true` allows to have top-level `await` expressions. They are + still not allowed in non-`async` functions, though. + +- **allowHashBang**: When this is enabled (off by default), if the + code starts with the characters `#!` (as in a shellscript), the + first line will be treated as a comment. + +- **locations**: When `true`, each node has a `loc` object attached + with `start` and `end` subobjects, each of which contains the + one-based line and zero-based column numbers in `{line, column}` + form. Default is `false`. + +- **onToken**: If a function is passed for this option, each found + token will be passed in same format as tokens returned from + `tokenizer().getToken()`. + + If array is passed, each found token is pushed to it. + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **onComment**: If a function is passed for this option, whenever a + comment is encountered the function will be called with the + following parameters: + + - `block`: `true` if the comment is a block comment, false if it + is a line comment. + - `text`: The content of the comment. + - `start`: Character offset of the start of the comment. + - `end`: Character offset of the end of the comment. + + When the `locations` options is on, the `{line, column}` locations + of the comment’s start and end are passed as two additional + parameters. + + If array is passed for this option, each found comment is pushed + to it as object in Esprima format: + + ```javascript + { + "type": "Line" | "Block", + "value": "comment text", + "start": Number, + "end": Number, + // If `locations` option is on: + "loc": { + "start": {line: Number, column: Number} + "end": {line: Number, column: Number} + }, + // If `ranges` option is on: + "range": [Number, Number] + } + ``` + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **ranges**: Nodes have their start and end characters offsets + recorded in `start` and `end` properties (directly on the node, + rather than the `loc` object, which holds line/column data. To also + add a + [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) + `range` property holding a `[start, end]` array with the same + numbers, set the `ranges` option to `true`. + +- **program**: It is possible to parse multiple files into a single + AST by passing the tree produced by parsing the first file as the + `program` option in subsequent parses. This will add the toplevel + forms of the parsed file to the "Program" (top) node of an existing + parse tree. + +- **sourceFile**: When the `locations` option is `true`, you can pass + this option to add a `source` attribute in every node’s `loc` + object. Note that the contents of this option are not examined or + processed in any way; you are free to use whatever format you + choose. + +- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property + will be added (regardless of the `location` option) directly to the + nodes, rather than the `loc` object. + +- **preserveParens**: If this option is `true`, parenthesized expressions + are represented by (non-standard) `ParenthesizedExpression` nodes + that have a single `expression` property containing the expression + inside parentheses. + +**parseExpressionAt**`(input, offset, options)` will parse a single +expression in a string, and return its AST. It will not complain if +there is more of the string left after the expression. + +**tokenizer**`(input, options)` returns an object with a `getToken` +method that can be called repeatedly to get the next token, a `{start, +end, type, value}` object (with added `loc` property when the +`locations` option is enabled and `range` property when the `ranges` +option is enabled). When the token's type is `tokTypes.eof`, you +should stop calling the method, since it will keep returning that same +token forever. + +In ES6 environment, returned result can be used as any other +protocol-compliant iterable: + +```javascript +for (let token of acorn.tokenizer(str)) { + // iterate over the tokens +} + +// transform code to array of tokens: +var tokens = [...acorn.tokenizer(str)]; +``` + +**tokTypes** holds an object mapping names to the token type objects +that end up in the `type` properties of tokens. + +**getLineInfo**`(input, offset)` can be used to get a `{line, +column}` object for a given program string and offset. + +### The `Parser` class + +Instances of the **`Parser`** class contain all the state and logic +that drives a parse. It has static methods `parse`, +`parseExpressionAt`, and `tokenizer` that match the top-level +functions by the same name. + +When extending the parser with plugins, you need to call these methods +on the extended version of the class. To extend a parser with plugins, +you can use its static `extend` method. + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +var JSXParser = acorn.Parser.extend(jsx()); +JSXParser.parse("foo()"); +``` + +The `extend` method takes any number of plugin values, and returns a +new `Parser` class that includes the extra parser logic provided by +the plugins. + +## Command line interface + +The `bin/acorn` utility can be used to parse a file from the command +line. It accepts as arguments its input file and the following +options: + +- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version + to parse. Default is version 9. + +- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. + +- `--locations`: Attaches a "loc" object to each node with "start" and + "end" subobjects, each of which contains the one-based line and + zero-based column numbers in `{line, column}` form. + +- `--allow-hash-bang`: If the code starts with the characters #! (as + in a shellscript), the first line will be treated as a comment. + +- `--compact`: No whitespace is used in the AST output. + +- `--silent`: Do not output the AST, just return the exit status. + +- `--help`: Print the usage information and quit. + +The utility spits out the syntax tree as JSON data. + +## Existing plugins + + - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) + +Plugins for ECMAScript proposals: + + - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: + - [`acorn-async-iteration`](https://github.com/acornjs/acorn-async-iteration): Parse [async iteration proposal](https://github.com/tc39/proposal-async-iteration) + - [`acorn-bigint`](https://github.com/acornjs/acorn-bigint): Parse [BigInt proposal](https://github.com/tc39/proposal-bigint) + - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) + - [`acorn-dynamic-import`](https://github.com/kesne/acorn-dynamic-import): Parse [import() proposal](https://github.com/tc39/proposal-dynamic-import) + - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) + - [`acorn-numeric-separator`](https://github.com/acornjs/acorn-numeric-separator): Parse [numeric separator proposal](https://github.com/tc39/proposal-numeric-separator) + - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n + +# @LOCALMOD XXX EMSCRIPTEN + +Add a quote of the erroring text on parse errors, and point to where it is, search for `XXX EMSCRIPTEN` in `acorn.js`, https://github.com/acornjs/acorn/pull/793 + diff --git a/tools/node_modules/acorn/dist/acorn.js b/tools/node_modules/acorn/dist/acorn.js new file mode 100644 index 0000000000000..fc3a2405267fc --- /dev/null +++ b/tools/node_modules/acorn/dist/acorn.js @@ -0,0 +1,5341 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.acorn = {}))); +}(this, (function (exports) { 'use strict'; + +// Reserved word lists for various dialects of the language + +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +}; + +// And the keywords + +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + +var keywords = { + 5: ecma5AndLessKeywords, + 6: ecma5AndLessKeywords + " const class extends export import super" +}; + +var keywordRelationalOperator = /^in(stanceof)?$/; + +// ## Character categories + +// Big ugly regular expressions that match characters in the +// whitespace, identifier, and identifier-start categories. These +// are only applied when a character is found to actually have a +// code point above 128. +// Generated by `bin/generate-identifier-regex.js`. + +var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + +// These are a run-length and offset encoded representation of the +// >0xffff code points that are a valid part of identifiers. The +// offset starts at 0x10000, and each pair of numbers represents an +// offset to the next range, and then a size of the range. They were +// generated by bin/generate-identifier-regex.js + +// eslint-disable-next-line comma-spacing +var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,190,52,76,44,33,24,27,35,30,0,12,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,26,230,43,117,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,68,12,0,67,12,65,1,31,6129,15,754,9486,286,82,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541]; + +// eslint-disable-next-line comma-spacing +var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]; + +// This has a complexity linear to the value of the code. The +// assumption is that looking up astral identifier characters is +// rare. +function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } +} + +// Test whether a given character code starts an identifier. + +function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) +} + +// Test whether a given character is part of an identifier. + +function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) +} + +// ## Token types + +// The assignment of fine-grained, information-carrying type objects +// allows the tokenizer to store the information it has about a +// token in a way that is very cheap for the parser to look up. + +// All token type variables start with an underscore, to make them +// easy to recognize. + +// The `beforeExpr` property is used to disambiguate between regular +// expressions and divisions. It is set on all token types that can +// be followed by an expression (thus, a slash after them would be a +// regular expression). +// +// The `startsExpr` property is used to check if the token ends a +// `yield` expression. It is set on all token types that either can +// directly start an expression (like a quotation mark) or can +// continue an expression (like the body of a string). +// +// `isLoop` marks a keyword as starting a loop, which is important +// to know when parsing a label, in order to allow or disallow +// continue jumps to that label. + +var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; +}; + +function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) +} +var beforeExpr = {beforeExpr: true}; +var startsExpr = {startsExpr: true}; + +// Map keyword names to token types. + +var keywords$1 = {}; + +// Succinct definitions of keyword token types +function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords$1[name] = new TokenType(name, options) +} + +var types = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import"), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) +}; + +// Matches a whole line break (where CRLF is considered a single +// line break). Used to count lines. + +var lineBreak = /\r\n?|\n|\u2028|\u2029/; +var lineBreakG = new RegExp(lineBreak.source, "g"); + +function isNewLine(code, ecma2019String) { + return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) +} + +var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + +var ref = Object.prototype; +var hasOwnProperty = ref.hasOwnProperty; +var toString = ref.toString; + +// Checks if an object has a property. + +function has(obj, propName) { + return hasOwnProperty.call(obj, propName) +} + +var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" +); }); + +// These are used when `options.locations` is on, for the +// `startLoc` and `endLoc` properties. + +var Position = function Position(line, col) { + this.line = line; + this.column = col; +}; + +Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) +}; + +var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } +}; + +// The `getLineInfo` function is mostly useful when the +// `locations` option is off (for performance reasons) and you +// want to find the line/column position for a given character +// offset. `input` should be the code string that the offset refers +// into. + +function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreakG.lastIndex = cur; + var match = lineBreakG.exec(input); + if (match && match.index < offset) { + ++line; + cur = match.index + match[0].length; + } else { + return new Position(line, offset - cur) + } + } +} + +// A second optional argument can be given to further configure +// the parser process. These options are recognized: + +var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10 + // (2019). This influences support for strict mode, the set of + // reserved words, and support for new syntax features. The default + // is 9. + ecmaVersion: 9, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // the position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program. + allowImportExportEverywhere: false, + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: false, + // When enabled, hashbang directive in the beginning of file + // is allowed and treated as a line comment. + allowHashBang: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false +}; + +// Interpret and default an options object + +function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion >= 2015) + { options.ecmaVersion -= 2009; } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options +} + +function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } +} + +// Each scope gets a bitset that may contain these flags +var SCOPE_TOP = 1; +var SCOPE_FUNCTION = 2; +var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION; +var SCOPE_ASYNC = 4; +var SCOPE_GENERATOR = 8; +var SCOPE_ARROW = 16; +var SCOPE_SIMPLE_CATCH = 32; +var SCOPE_SUPER = 64; +var SCOPE_DIRECT_SUPER = 128; + +function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) +} + +// Used in checkLVal and declareName to determine the type of a binding +var BIND_NONE = 0; +var BIND_VAR = 1; +var BIND_LEXICAL = 2; +var BIND_FUNCTION = 3; +var BIND_SIMPLE_CATCH = 4; +var BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + +function keywordRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") +} + +var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]); + var reserved = ""; + if (!options.allowReserved) { + for (var v = options.ecmaVersion;; v--) + { if (reserved = reservedWords[v]) { break } } + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = keywordRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = keywordRegexp(reservedStrict); + this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = 0; + // Labels in scope. + this.labels = []; + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; +}; + +var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true } }; + +Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) +}; + +prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; +prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; +prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; +prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; +prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + +// Switch to a getter for 7.0.0. +Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; + +Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls +}; + +Parser.parse = function parse (input, options) { + return new this(options, input).parse() +}; + +Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() +}; + +Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) +}; + +Object.defineProperties( Parser.prototype, prototypeAccessors ); + +var pp = Parser.prototype; + +// ## Parser utilities + +var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/; +pp.strictDirective = function(start) { + var this$1 = this; + + for (;;) { + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this$1.input)[0].length; + var match = literal.exec(this$1.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { return true } + start += match[0].length; + } +}; + +// Predicate that tests whether the next token is of the given +// type, and if yes, consumes it as a side effect. + +pp.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } +}; + +// Tests whether parsed token is a contextual keyword. + +pp.isContextual = function(name) { + return this.type === types.name && this.value === name && !this.containsEsc +}; + +// Consumes contextual keyword if possible. + +pp.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true +}; + +// Asserts that following token is given contextual keyword. + +pp.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } +}; + +// Test whether a semicolon can be inserted at the current position. + +pp.canInsertSemicolon = function() { + return this.type === types.eof || + this.type === types.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +}; + +pp.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } +}; + +// Consume a semicolon, or, failing that, see if we are allowed to +// pretend that there is a semicolon at this position. + +pp.semicolon = function() { + if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } +}; + +pp.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } +}; + +// Expect a token of a given type. If found, consume it, otherwise, +// raise an unexpected token error. + +pp.expect = function(type) { + this.eat(type) || this.unexpected(); +}; + +// Raise an unexpected token error. + +pp.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); +}; + +function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; +} + +pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } +}; + +pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } +}; + +pp.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } +}; + +pp.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" +}; + +var pp$1 = Parser.prototype; + +// ### Statement parsing + +// Parse a program. Initializes the parser, reads any number of +// statements, and wraps them in a Program node. Optionally takes a +// `program` argument. If present, the statements will be appended +// to its body instead of creating a new node. + +pp$1.parseTopLevel = function(node) { + var this$1 = this; + + var exports = {}; + if (!node.body) { node.body = []; } + while (this.type !== types.eof) { + var stmt = this$1.parseStatement(null, true, exports); + node.body.push(stmt); + } + this.adaptDirectivePrologue(node.body); + this.next(); + if (this.options.ecmaVersion >= 6) { + node.sourceType = this.options.sourceType; + } + return this.finishNode(node, "Program") +}; + +var loopLabel = {kind: "loop"}; +var switchLabel = {kind: "switch"}; + +pp$1.isLet = function() { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 123 && !lineBreak.test(this.input.slice(this.end, next)) // '{' + || nextCh === 91) { return true } // '[' + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false +}; + +// check 'async [no LineTerminator here] function' +// - 'async /*foo*/ function' is OK. +// - 'async /*\n*/ function' is invalid. +pp$1.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) +}; + +// Parse a single statement. +// +// If expecting a statement and finding a slash operator, parse a +// regular expression literal. This is to handle cases like +// `if (foo) /blah/.exec(foo)`, where looking at the previous token +// does not help. + +pp$1.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet()) { + starttype = types._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types._debugger: return this.parseDebuggerStatement(node) + case types._do: return this.parseDoStatement(node) + case types._for: return this.parseForStatement(node) + case types._function: + if ((context && (this.strict || context !== "if")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types._if: return this.parseIfStatement(node) + case types._return: return this.parseReturnStatement(node) + case types._switch: return this.parseSwitchStatement(node) + case types._throw: return this.parseThrowStatement(node) + case types._try: return this.parseTryStatement(node) + case types._const: case types._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types._while: return this.parseWhileStatement(node) + case types._with: return this.parseWithStatement(node) + case types.braceL: return this.parseBlock(true, node) + case types.semi: return this.parseEmptyStatement(node) + case types._export: + case types._import: + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } +}; + +pp$1.parseBreakContinueStatement = function(node, keyword) { + var this$1 = this; + + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this$1.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") +}; + +pp$1.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") +}; + +pp$1.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") +}; + +// Disambiguating between a `for` and a `for`/`in` or `for`/`of` +// loop is non-trivial. Basically, we have to parse the init `var` +// statement or expression, disallowing the `in` operator (see +// the second parameter to `parseExpression`), and then check +// whether the next token is `in` or `of`. When there is no init +// part (semicolon immediately after the opening parenthesis), it +// is a regular `for` loop. + +pp$1.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types.parenL); + if (this.type === types.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types._var || this.type === types._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && + !(kind !== "var" && init$1.declarations[0].init)) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(true, refDestructuringErrors); + if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLVal(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) +}; + +pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) +}; + +pp$1.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") +}; + +pp$1.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") +}; + +pp$1.parseSwitchStatement = function(node) { + var this$1 = this; + + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types.braceR;) { + if (this$1.type === types._case || this$1.type === types._default) { + var isCase = this$1.type === types._case; + if (cur) { this$1.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this$1.startNode()); + cur.consequent = []; + this$1.next(); + if (isCase) { + cur.test = this$1.parseExpression(); + } else { + if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this$1.expect(types.colon); + } else { + if (!cur) { this$1.unexpected(); } + cur.consequent.push(this$1.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") +}; + +pp$1.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") +}; + +// Reused empty array added for node fields that are always empty. + +var empty = []; + +pp$1.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types.parenL)) { + clause.param = this.parseBindingAtom(); + var simple = clause.param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types.parenR); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") +}; + +pp$1.parseVarStatement = function(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") +}; + +pp$1.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") +}; + +pp$1.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") +}; + +pp$1.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") +}; + +pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { + var this$1 = this; + + for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this$1.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this$1.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context); + if (node.body.type === "ClassDeclaration" || + node.body.type === "VariableDeclaration" && node.body.kind !== "var" || + node.body.type === "FunctionDeclaration" && (this.strict || node.body.generator || node.body.async)) + { this.raiseRecoverable(node.body.start, "Invalid labeled declaration"); } + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") +}; + +pp$1.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") +}; + +// Parse a semicolon-enclosed block of statements, handling `"use +// strict"` declarations when `allowStrict` is true (used for +// function bodies). + +pp$1.parseBlock = function(createNewLexicalScope, node) { + var this$1 = this; + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (!this.eat(types.braceR)) { + var stmt = this$1.parseStatement(null); + node.body.push(stmt); + } + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") +}; + +// Parse a regular `for` loop. The disambiguation code in +// `parseStatement` will already have parsed the init statement or +// expression. + +pp$1.parseFor = function(node, init) { + node.init = init; + this.expect(types.semi); + node.test = this.type === types.semi ? null : this.parseExpression(); + this.expect(types.semi); + node.update = this.type === types.parenR ? null : this.parseExpression(); + this.expect(types.parenR); + this.exitScope(); + node.body = this.parseStatement("for"); + this.labels.pop(); + return this.finishNode(node, "ForStatement") +}; + +// Parse a `for`/`in` and `for`/`of` loop, which are almost +// same from parser's perspective. + +pp$1.parseForIn = function(node, init) { + var type = this.type === types._in ? "ForInStatement" : "ForOfStatement"; + this.next(); + if (type === "ForInStatement") { + if (init.type === "AssignmentPattern" || + (init.type === "VariableDeclaration" && init.declarations[0].init != null && + (this.strict || init.declarations[0].id.type !== "Identifier"))) + { this.raise(init.start, "Invalid assignment in for-in loop head"); } + } + node.left = init; + node.right = type === "ForInStatement" ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types.parenR); + this.exitScope(); + node.body = this.parseStatement("for"); + this.labels.pop(); + return this.finishNode(node, type) +}; + +// Parse a list of variable declarations. + +pp$1.parseVar = function(node, isFor, kind) { + var this$1 = this; + + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this$1.startNode(); + this$1.parseVarId(decl, kind); + if (this$1.eat(types.eq)) { + decl.init = this$1.parseMaybeAssign(isFor); + } else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { + this$1.unexpected(); + } else if (decl.id.type !== "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) { + this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")); + if (!this$1.eat(types.comma)) { break } + } + return node +}; + +pp$1.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(kind); + this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); +}; + +var FUNC_STATEMENT = 1; +var FUNC_HANGING_STATEMENT = 2; +var FUNC_NULLABLE_ID = 4; + +// Parse a function declaration or literal (depending on the +// `isStatement` parameter). + +pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) + { node.generator = this.eat(types.star); } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + { this.checkLVal(node.id, this.inModule && !this.inFunction ? BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") +}; + +pp$1.parseFunctionParams = function(node) { + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); +}; + +// Parse a class declaration or literal (depending on the +// `isStatement` parameter). + +pp$1.parseClass = function(node, isStatement) { + var this$1 = this; + + this.next(); + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + var element = this$1.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this$1.raise(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } + } + } + node.body = this.finishNode(classBody, "ClassBody"); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") +}; + +pp$1.parseClassElement = function(constructorAllowsSuper) { + var this$1 = this; + + if (this.eat(types.semi)) { return null } + + var method = this.startNode(); + var tryContextual = function (k, noLineBreak) { + if ( noLineBreak === void 0 ) noLineBreak = false; + + var start = this$1.start, startLoc = this$1.startLoc; + if (!this$1.eatContextual(k)) { return false } + if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } + if (method.key) { this$1.unexpected(); } + method.computed = false; + method.key = this$1.startNodeAt(start, startLoc); + method.key.name = k; + this$1.finishNode(method.key, "Identifier"); + return false + }; + + method.kind = "method"; + method.static = tryContextual("static"); + var isGenerator = this.eat(types.star); + var isAsync = false; + if (!isGenerator) { + if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); + } else if (tryContextual("get")) { + method.kind = "get"; + } else if (tryContextual("set")) { + method.kind = "set"; + } + } + if (!method.key) { this.parsePropertyName(method); } + var key = method.key; + var allowsDirectSuper = false; + if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || + key.type === "Literal" && key.value === "constructor")) { + if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + method.kind = "constructor"; + allowsDirectSuper = constructorAllowsSuper; + } else if (method.static && key.type === "Identifier" && key.name === "prototype") { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); + if (method.kind === "get" && method.value.params.length !== 0) + { this.raiseRecoverable(method.value.start, "getter should have no params"); } + if (method.kind === "set" && method.value.params.length !== 1) + { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } + if (method.kind === "set" && method.value.params[0].type === "RestElement") + { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } + return method +}; + +pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + return this.finishNode(method, "MethodDefinition") +}; + +pp$1.parseClassId = function(node, isStatement) { + node.id = this.type === types.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null; +}; + +pp$1.parseClassSuper = function(node) { + node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; +}; + +// Parses module export declaration. + +pp$1.parseExport = function(node, exports) { + var this$1 = this; + + this.next(); + // export * from '...' + if (this.eat(types.star)) { + this.expectContextual("from"); + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + } + if (this.eat(types._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + var isAsync; + if (this.type === types._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync, true); + } else if (this.type === types._class) { + var cNode = this.startNode(); + node.declaration = this.parseClass(cNode, "nullableID"); + } else { + node.declaration = this.parseMaybeAssign(); + this.semicolon(); + } + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(null); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + // check for keywords used as local names + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + var spec = list[i]; + + this$1.checkUnreserved(spec.local); + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") +}; + +pp$1.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (has(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; +}; + +pp$1.checkPatternExport = function(exports, pat) { + var this$1 = this; + + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat.name, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this$1.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this$1.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + else if (type === "ParenthesizedExpression") + { this.checkPatternExport(exports, pat.expression); } +}; + +pp$1.checkVariableExport = function(exports, decls) { + var this$1 = this; + + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this$1.checkPatternExport(exports, decl.id); + } +}; + +pp$1.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() +}; + +// Parses a comma-separated list of module exports. + +pp$1.parseExportSpecifiers = function(exports) { + var this$1 = this; + + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this$1.expect(types.comma); + if (this$1.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node = this$1.startNode(); + node.local = this$1.parseIdent(true); + node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local; + this$1.checkExport(exports, node.exported.name, node.exported.start); + nodes.push(this$1.finishNode(node, "ExportSpecifier")); + } + return nodes +}; + +// Parses import declaration. + +pp$1.parseImport = function(node) { + this.next(); + // import '...' + if (this.type === types.string) { + node.specifiers = empty; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") +}; + +// Parses a comma-separated list of module imports. + +pp$1.parseImportSpecifiers = function() { + var this$1 = this; + + var nodes = [], first = true; + if (this.type === types.name) { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLVal(node.local, BIND_LEXICAL); + nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); + if (!this.eat(types.comma)) { return nodes } + } + if (this.type === types.star) { + var node$1 = this.startNode(); + this.next(); + this.expectContextual("as"); + node$1.local = this.parseIdent(); + this.checkLVal(node$1.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); + return nodes + } + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this$1.expect(types.comma); + if (this$1.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node$2 = this$1.startNode(); + node$2.imported = this$1.parseIdent(true); + if (this$1.eatContextual("as")) { + node$2.local = this$1.parseIdent(); + } else { + this$1.checkUnreserved(node$2.imported); + node$2.local = node$2.imported; + } + this$1.checkLVal(node$2.local, BIND_LEXICAL); + nodes.push(this$1.finishNode(node$2, "ImportSpecifier")); + } + return nodes +}; + +// Set `ExpressionStatement#directive` property for directive prologues. +pp$1.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } +}; +pp$1.isDirectiveCandidate = function(statement) { + return ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) +}; + +var pp$2 = Parser.prototype; + +// Convert existing expression atom to assignable pattern +// if possible. + +pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { + var this$1 = this; + + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Can not use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this$1.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this$1.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + // falls through to AssignmentPattern + + case "AssignmentPattern": + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node +}; + +// Convert list of expression atoms to binding list. + +pp$2.toAssignableList = function(exprList, isBinding) { + var this$1 = this; + + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this$1.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList +}; + +// Parses spread element. + +pp$2.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") +}; + +pp$2.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") +}; + +// Parses lvalue (assignable) atom. + +pp$2.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() +}; + +pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { + var this$1 = this; + + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this$1.expect(types.comma); } + if (allowEmpty && this$1.type === types.comma) { + elts.push(null); + } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { + break + } else if (this$1.type === types.ellipsis) { + var rest = this$1.parseRestBinding(); + this$1.parseBindingListItem(rest); + elts.push(rest); + if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); } + this$1.expect(close); + break + } else { + var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc); + this$1.parseBindingListItem(elem); + elts.push(elem); + } + } + return elts +}; + +pp$2.parseBindingListItem = function(param) { + return param +}; + +// Parses assignment pattern around given atom if possible. + +pp$2.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") +}; + +// Verify that a node is an lval — something that can be assigned +// to. +// bindingType can be either: +// 'var' indicating that the lval creates a 'var' binding +// 'let' indicating that the lval creates a lexical ('let' or 'const') binding +// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references + +pp$2.checkLVal = function(expr, bindingType, checkClashes) { + var this$1 = this; + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (checkClashes) { + if (has(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + break + + case "MemberExpression": + if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this$1.checkLVal(prop, bindingType, checkClashes); + } + break + + case "Property": + // AssignmentProperty has type === "Property" + this.checkLVal(expr.value, bindingType, checkClashes); + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); } + } + break + + case "AssignmentPattern": + this.checkLVal(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLVal(expr.argument, bindingType, checkClashes); + break + + case "ParenthesizedExpression": + this.checkLVal(expr.expression, bindingType, checkClashes); + break + + default: + this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); + } +}; + +// A recursive descent parser operates by defining functions for all +// syntactic elements, and recursively calling those, each function +// advancing the input stream and returning an AST node. Precedence +// of constructs (for example, the fact that `!x[1]` means `!(x[1])` +// instead of `(!x)[1]` is handled by the fact that the parser +// function that parses unary prefix operators is called first, and +// in turn calls the function that parses `[]` subscripts — that +// way, it'll receive the node for `x[1]` already parsed, and wraps +// *that* in the unary operator node. +// +// Acorn uses an [operator precedence parser][opp] to handle binary +// operator precedence, because it is much more compact than using +// the technique outlined above, which uses different, nesting +// functions to specify precedence, for all of the ten binary +// precedence levels that JavaScript defines. +// +// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + +var pp$3 = Parser.prototype; + +// Check if property name clashes with already added. +// Object/class getters and setters are not allowed to clash — +// either with each other or with an init property — and in +// strict mode, init properties are also not allowed to be repeated. + +pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } + // Backwards-compat kludge. Can be removed in version 6.0 + else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; +}; + +// ### Expression parsing + +// These nest, from the most general expression type at the top to +// 'atomic', nondivisible expression types at the bottom. Most of +// the functions will simply let the function(s) below them parse, +// and, *if* the syntactic construct they handle is present, wrap +// the AST node that the inner parser gave them in another node. + +// Parse a full expression. The optional arguments are used to +// forbid the `in` operator (in for loops initalization expressions) +// and provide reference for storing '=' operator inside shorthand +// property assignment in contexts where both object expression +// and object pattern might appear (so it's possible to raise +// delayed syntax error at correct position). + +pp$3.parseExpression = function(noIn, refDestructuringErrors) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); + if (this.type === types.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr +}; + +// Parse an assignment expression. This includes applications of +// operators like `+=`. + +pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield() } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldShorthandAssign = refDestructuringErrors.shorthandAssign; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types.parenL || this.type === types.name) + { this.potentialArrowAt = this.start; } + var left = this.parseMaybeConditional(noIn, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; + if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); } + refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly + this.checkLVal(left); + this.next(); + node.right = this.parseMaybeAssign(noIn); + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; } + return left +}; + +// Parse a ternary conditional (`?:`) operator. + +pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(noIn, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types.colon); + node.alternate = this.parseMaybeAssign(noIn); + return this.finishNode(node, "ConditionalExpression") + } + return expr +}; + +// Start the precedence parser. + +pp$3.parseExprOps = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) +}; + +// Parse binary operators with the operator precedence parsing +// algorithm. `left` is the left-hand side of the operator. +// `minPrec` provides context that allows the function to stop and +// defer further parser to one of its callers when it encounters an +// operator that has a lower precedence than the set it is parsing. + +pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.type.binop; + if (prec != null && (!noIn || this.type !== types._in)) { + if (prec > minPrec) { + var logical = this.type === types.logicalOR || this.type === types.logicalAND; + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) + } + } + return left +}; + +pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") +}; + +// Parse unary operators, both prefix and postfix. + +pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { + expr = this.parseAwait(); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLVal(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else { + expr = this.parseExprSubscripts(refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this$1.startNodeAt(startPos, startLoc); + node$1.operator = this$1.value; + node$1.prefix = false; + node$1.argument = expr; + this$1.checkLVal(expr); + this$1.next(); + expr = this$1.finishNode(node$1, "UpdateExpression"); + } + } + + if (!sawUnary && this.eat(types.starstar)) + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } + else + { return expr } +}; + +// Parse call, dot, and `[]`-subscript expressions. + +pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors); + var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; + if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + } + return result +}; + +pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { + var this$1 = this; + + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; + for (var computed = (void 0);;) { + if ((computed = this$1.eat(types.bracketL)) || this$1.eat(types.dot)) { + var node = this$1.startNodeAt(startPos, startLoc); + node.object = base; + node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true); + node.computed = !!computed; + if (computed) { this$1.expect(types.bracketR); } + base = this$1.finishNode(node, "MemberExpression"); + } else if (!noCalls && this$1.eat(types.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos; + this$1.yieldPos = 0; + this$1.awaitPos = 0; + var exprList = this$1.parseExprList(types.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(types.arrow)) { + this$1.checkPatternErrors(refDestructuringErrors, false); + this$1.checkYieldAwaitInDefaultParams(); + this$1.yieldPos = oldYieldPos; + this$1.awaitPos = oldAwaitPos; + return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true) + } + this$1.checkExpressionErrors(refDestructuringErrors, true); + this$1.yieldPos = oldYieldPos || this$1.yieldPos; + this$1.awaitPos = oldAwaitPos || this$1.awaitPos; + var node$1 = this$1.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + base = this$1.finishNode(node$1, "CallExpression"); + } else if (this$1.type === types.backQuote) { + var node$2 = this$1.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this$1.parseTemplate({isTagged: true}); + base = this$1.finishNode(node$2, "TaggedTemplateExpression"); + } else { + return base + } + } +}; + +// Parse an atomic expression — either a single token that is an +// expression, an expression started by a keyword like `function` or +// `new`, or an expression wrapped in punctuation like `()`, `[]`, +// or `{}`. + +pp$3.parseExprAtom = function(refDestructuringErrors) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super Arguments + if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(this.type !== types.name); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) + { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { + id = this.parseIdent(); + if (this.canInsertSemicolon() || !this.eat(types.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) + } + } + return id + + case types.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types.num: case types.string: + return this.parseLiteral(this.value) + + case types._null: case types._true: case types._false: + node = this.startNode(); + node.value = this.type === types._null ? null : this.type === types._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types.braceL: + return this.parseObj(false, refDestructuringErrors) + + case types._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types._class: + return this.parseClass(this.startNode(), false) + + case types._new: + return this.parseNew() + + case types.backQuote: + return this.parseTemplate() + + default: + this.unexpected(); + } +}; + +pp$3.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + this.next(); + return this.finishNode(node, "Literal") +}; + +pp$3.parseParenExpression = function() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val +}; + +pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + while (this.type !== types.parenR) { + first ? first = false : this$1.expect(types.comma); + if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) { + lastIsComma = true; + break + } else if (this$1.type === types.ellipsis) { + spreadStart = this$1.start; + exprList.push(this$1.parseParenItem(this$1.parseRestBinding())); + if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); } + break + } else { + exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)); + } + } + var innerEndPos = this.start, innerEndLoc = this.startLoc; + this.expect(types.parenR); + + if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } +}; + +pp$3.parseParenItem = function(item) { + return item +}; + +pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) +}; + +// New's precedence is slightly tricky. It must allow its argument to +// be a `[]` or dot subscript expression, but not a call — at least, +// not without wrapping it in parentheses. Thus, it uses the noCalls +// argument to parseSubscripts to prevent it from consuming the +// argument list. + +var empty$1 = []; + +pp$3.parseNew = function() { + var node = this.startNode(); + var meta = this.parseIdent(true); + if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { + node.meta = meta; + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target" || containsEsc) + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); } + if (!this.inNonArrowFunction()) + { this.raiseRecoverable(node.start, "new.target can only be used in functions"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); + if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty$1; } + return this.finishNode(node, "NewExpression") +}; + +// Parse template expression. + +pp$3.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types.backQuote; + return this.finishNode(elem, "TemplateElement") +}; + +pp$3.parseTemplate = function(ref) { + var this$1 = this; + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this$1.type === types.eof) { this$1.raise(this$1.pos, "Unterminated template literal"); } + this$1.expect(types.dollarBraceL); + node.expressions.push(this$1.parseExpression()); + this$1.expect(types.braceR); + node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") +}; + +pp$3.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +}; + +// Parse an object literal or binding pattern. + +pp$3.parseObj = function(isPattern, refDestructuringErrors) { + var this$1 = this; + + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types.braceR)) { + if (!first) { + this$1.expect(types.comma); + if (this$1.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var prop = this$1.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this$1.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") +}; + +pp$3.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // To disallow parenthesized identifier via `this.toAssignable()`. + if (this.type === types.parenL && refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0) { + refDestructuringErrors.parenthesizedAssign = this.start; + } + if (refDestructuringErrors.parenthesizedBind < 0) { + refDestructuringErrors.parenthesizedBind = this.start; + } + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); + this.parsePropertyName(prop, refDestructuringErrors); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") +}; + +pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types.colon) + { this.unexpected(); } + + if (this.eat(types.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types.comma && this.type !== types.braceR)) { + if (isGenerator || isAsync) { this.unexpected(); } + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + this.checkUnreserved(prop.key); + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); + } else if (this.type === types.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); + } else { + prop.value = prop.key; + } + prop.shorthand = true; + } else { this.unexpected(); } +}; + +pp$3.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true) +}; + +// Initialize empty function node. + +pp$3.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } +}; + +// Parse object or class method. + +pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.finishNode(node, "FunctionExpression") +}; + +// Parse arrow function expression with given parameters. + +pp$3.parseArrowExpression = function(node, params, isAsync) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.finishNode(node, "ArrowFunctionExpression") +}; + +// Parse function body and check parameters. + +pp$3.parseFunctionBody = function(node, isArrowFunction) { + var isExpression = isArrowFunction && this.type !== types.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params)); + node.body = this.parseBlock(false); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } + this.strict = oldStrict; +}; + +pp$3.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true +}; + +// Checks function params for various disallowed patterns such as using "eval" +// or "arguments" and duplicate parameters. + +pp$3.checkParams = function(node, allowDuplicates) { + var this$1 = this; + + var nameHash = {}; + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this$1.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash); + } +}; + +// Parses a comma-separated list of expressions, and returns them as +// an array. `close` is the token type that ends the list, and +// `allowEmpty` can be turned on to allow subsequent commas with +// nothing in between them to be parsed as `null` (which is needed +// for array literals). + +pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var this$1 = this; + + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this$1.expect(types.comma); + if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this$1.type === types.comma) + { elt = null; } + else if (this$1.type === types.ellipsis) { + elt = this$1.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this$1.start; } + } else { + elt = this$1.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts +}; + +pp$3.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Can not use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Can not use 'await' as identifier inside an async function"); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Can not use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } +}; + +// Parse the next token as an identifier. If `liberal` is true (used +// when parsing properties), it will also convert keywords into +// identifiers. + +pp$3.parseIdent = function(liberal, isBinding) { + var node = this.startNode(); + if (liberal && this.options.allowReserved === "never") { liberal = false; } + if (this.type === types.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "Identifier"); + if (!liberal) { this.checkUnreserved(node); } + return node +}; + +// Parses yield expression inside generator. + +pp$3.parseYield = function() { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types.star); + node.argument = this.parseMaybeAssign(); + } + return this.finishNode(node, "YieldExpression") +}; + +pp$3.parseAwait = function() { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + return this.finishNode(node, "AwaitExpression") +}; + +var pp$4 = Parser.prototype; + +// This function is used to raise exceptions on parse errors. It +// takes an offset integer (into the current `input`) to indicate +// the location of the error, attaches the position to the end +// of the error message, and then raises a `SyntaxError` with that +// message. + +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + // XXX EMSCRIPTEN: add a quote of the error text, point to where + // https://github.com/acornjs/acorn/pull/793 + var lines = this.input.split('\n'); + message = message + '\n' + lines[loc.line - 1] + '\n'; + for (var i = 0; i < loc.column; i++) { + message += ' '; + } + message += '^\n'; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err +}; + +pp$4.raiseRecoverable = pp$4.raise; + +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } +}; + +var pp$5 = Parser.prototype; + +var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; +}; + +// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + +pp$5.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); +}; + +pp$5.exitScope = function() { + this.scopeStack.pop(); +}; + +pp$5.declareName = function(name, bindingType, pos) { + var this$1 = this; + + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + redeclared = scope$2.lexical.indexOf(name) > -1; + scope$2.var.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this$1.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) { redeclared = true; } + scope$3.var.push(name); + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } +}; + +pp$5.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] +}; + +pp$5.currentVarScope = function() { + var this$1 = this; + + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this$1.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } +}; + +// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. +pp$5.currentThisScope = function() { + var this$1 = this; + + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this$1.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } +}; + +var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } +}; + +// Start an AST node, attaching a start offset. + +var pp$6 = Parser.prototype; + +pp$6.startNode = function() { + return new Node(this, this.start, this.startLoc) +}; + +pp$6.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) +}; + +// Finish an AST node, adding `type` and `end` properties. + +function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node +} + +pp$6.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) +}; + +// Finish node at given position + +pp$6.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) +}; + +// The algorithm used to determine whether a regexp can appear at a +// given point in the program is loosely based on sweet.js' approach. +// See https://github.com/mozilla/sweet.js/wiki/design + +var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; +}; + +var types$1 = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) +}; + +var pp$7 = Parser.prototype; + +pp$7.initialContext = function() { + return [types$1.b_stat] +}; + +pp$7.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types$1.f_expr || parent === types$1.f_stat) + { return true } + if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types._return || prevType === types.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) + { return true } + if (prevType === types.braceL) + { return parent === types$1.b_stat } + if (prevType === types._var || prevType === types._const || prevType === types.name) + { return false } + return !this.exprAllowed +}; + +pp$7.inGeneratorContext = function() { + var this$1 = this; + + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this$1.context[i]; + if (context.token === "function") + { return context.generator } + } + return false +}; + +pp$7.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } +}; + +// Token-specific context update code + +types.parenR.updateContext = types.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types$1.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; +}; + +types.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); + this.exprAllowed = true; +}; + +types.dollarBraceL.updateContext = function() { + this.context.push(types$1.b_tmpl); + this.exprAllowed = true; +}; + +types.parenL.updateContext = function(prevType) { + var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; + this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); + this.exprAllowed = true; +}; + +types.incDec.updateContext = function() { + // tokExprAllowed stays unchanged +}; + +types._function.updateContext = types._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && + !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) + { this.context.push(types$1.f_expr); } + else + { this.context.push(types$1.f_stat); } + this.exprAllowed = false; +}; + +types.backQuote.updateContext = function() { + if (this.curContext() === types$1.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types$1.q_tmpl); } + this.exprAllowed = false; +}; + +types.star.updateContext = function(prevType) { + if (prevType === types._function) { + var index = this.context.length - 1; + if (this.context[index] === types$1.f_expr) + { this.context[index] = types$1.f_expr_gen; } + else + { this.context[index] = types$1.f_gen; } + } + this.exprAllowed = true; +}; + +types.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; +}; + +var data = { + "$LONE": [ + "ASCII", + "ASCII_Hex_Digit", + "AHex", + "Alphabetic", + "Alpha", + "Any", + "Assigned", + "Bidi_Control", + "Bidi_C", + "Bidi_Mirrored", + "Bidi_M", + "Case_Ignorable", + "CI", + "Cased", + "Changes_When_Casefolded", + "CWCF", + "Changes_When_Casemapped", + "CWCM", + "Changes_When_Lowercased", + "CWL", + "Changes_When_NFKC_Casefolded", + "CWKCF", + "Changes_When_Titlecased", + "CWT", + "Changes_When_Uppercased", + "CWU", + "Dash", + "Default_Ignorable_Code_Point", + "DI", + "Deprecated", + "Dep", + "Diacritic", + "Dia", + "Emoji", + "Emoji_Component", + "Emoji_Modifier", + "Emoji_Modifier_Base", + "Emoji_Presentation", + "Extender", + "Ext", + "Grapheme_Base", + "Gr_Base", + "Grapheme_Extend", + "Gr_Ext", + "Hex_Digit", + "Hex", + "IDS_Binary_Operator", + "IDSB", + "IDS_Trinary_Operator", + "IDST", + "ID_Continue", + "IDC", + "ID_Start", + "IDS", + "Ideographic", + "Ideo", + "Join_Control", + "Join_C", + "Logical_Order_Exception", + "LOE", + "Lowercase", + "Lower", + "Math", + "Noncharacter_Code_Point", + "NChar", + "Pattern_Syntax", + "Pat_Syn", + "Pattern_White_Space", + "Pat_WS", + "Quotation_Mark", + "QMark", + "Radical", + "Regional_Indicator", + "RI", + "Sentence_Terminal", + "STerm", + "Soft_Dotted", + "SD", + "Terminal_Punctuation", + "Term", + "Unified_Ideograph", + "UIdeo", + "Uppercase", + "Upper", + "Variation_Selector", + "VS", + "White_Space", + "space", + "XID_Continue", + "XIDC", + "XID_Start", + "XIDS" + ], + "General_Category": [ + "Cased_Letter", + "LC", + "Close_Punctuation", + "Pe", + "Connector_Punctuation", + "Pc", + "Control", + "Cc", + "cntrl", + "Currency_Symbol", + "Sc", + "Dash_Punctuation", + "Pd", + "Decimal_Number", + "Nd", + "digit", + "Enclosing_Mark", + "Me", + "Final_Punctuation", + "Pf", + "Format", + "Cf", + "Initial_Punctuation", + "Pi", + "Letter", + "L", + "Letter_Number", + "Nl", + "Line_Separator", + "Zl", + "Lowercase_Letter", + "Ll", + "Mark", + "M", + "Combining_Mark", + "Math_Symbol", + "Sm", + "Modifier_Letter", + "Lm", + "Modifier_Symbol", + "Sk", + "Nonspacing_Mark", + "Mn", + "Number", + "N", + "Open_Punctuation", + "Ps", + "Other", + "C", + "Other_Letter", + "Lo", + "Other_Number", + "No", + "Other_Punctuation", + "Po", + "Other_Symbol", + "So", + "Paragraph_Separator", + "Zp", + "Private_Use", + "Co", + "Punctuation", + "P", + "punct", + "Separator", + "Z", + "Space_Separator", + "Zs", + "Spacing_Mark", + "Mc", + "Surrogate", + "Cs", + "Symbol", + "S", + "Titlecase_Letter", + "Lt", + "Unassigned", + "Cn", + "Uppercase_Letter", + "Lu" + ], + "Script": [ + "Adlam", + "Adlm", + "Ahom", + "Anatolian_Hieroglyphs", + "Hluw", + "Arabic", + "Arab", + "Armenian", + "Armn", + "Avestan", + "Avst", + "Balinese", + "Bali", + "Bamum", + "Bamu", + "Bassa_Vah", + "Bass", + "Batak", + "Batk", + "Bengali", + "Beng", + "Bhaiksuki", + "Bhks", + "Bopomofo", + "Bopo", + "Brahmi", + "Brah", + "Braille", + "Brai", + "Buginese", + "Bugi", + "Buhid", + "Buhd", + "Canadian_Aboriginal", + "Cans", + "Carian", + "Cari", + "Caucasian_Albanian", + "Aghb", + "Chakma", + "Cakm", + "Cham", + "Cherokee", + "Cher", + "Common", + "Zyyy", + "Coptic", + "Copt", + "Qaac", + "Cuneiform", + "Xsux", + "Cypriot", + "Cprt", + "Cyrillic", + "Cyrl", + "Deseret", + "Dsrt", + "Devanagari", + "Deva", + "Duployan", + "Dupl", + "Egyptian_Hieroglyphs", + "Egyp", + "Elbasan", + "Elba", + "Ethiopic", + "Ethi", + "Georgian", + "Geor", + "Glagolitic", + "Glag", + "Gothic", + "Goth", + "Grantha", + "Gran", + "Greek", + "Grek", + "Gujarati", + "Gujr", + "Gurmukhi", + "Guru", + "Han", + "Hani", + "Hangul", + "Hang", + "Hanunoo", + "Hano", + "Hatran", + "Hatr", + "Hebrew", + "Hebr", + "Hiragana", + "Hira", + "Imperial_Aramaic", + "Armi", + "Inherited", + "Zinh", + "Qaai", + "Inscriptional_Pahlavi", + "Phli", + "Inscriptional_Parthian", + "Prti", + "Javanese", + "Java", + "Kaithi", + "Kthi", + "Kannada", + "Knda", + "Katakana", + "Kana", + "Kayah_Li", + "Kali", + "Kharoshthi", + "Khar", + "Khmer", + "Khmr", + "Khojki", + "Khoj", + "Khudawadi", + "Sind", + "Lao", + "Laoo", + "Latin", + "Latn", + "Lepcha", + "Lepc", + "Limbu", + "Limb", + "Linear_A", + "Lina", + "Linear_B", + "Linb", + "Lisu", + "Lycian", + "Lyci", + "Lydian", + "Lydi", + "Mahajani", + "Mahj", + "Malayalam", + "Mlym", + "Mandaic", + "Mand", + "Manichaean", + "Mani", + "Marchen", + "Marc", + "Masaram_Gondi", + "Gonm", + "Meetei_Mayek", + "Mtei", + "Mende_Kikakui", + "Mend", + "Meroitic_Cursive", + "Merc", + "Meroitic_Hieroglyphs", + "Mero", + "Miao", + "Plrd", + "Modi", + "Mongolian", + "Mong", + "Mro", + "Mroo", + "Multani", + "Mult", + "Myanmar", + "Mymr", + "Nabataean", + "Nbat", + "New_Tai_Lue", + "Talu", + "Newa", + "Nko", + "Nkoo", + "Nushu", + "Nshu", + "Ogham", + "Ogam", + "Ol_Chiki", + "Olck", + "Old_Hungarian", + "Hung", + "Old_Italic", + "Ital", + "Old_North_Arabian", + "Narb", + "Old_Permic", + "Perm", + "Old_Persian", + "Xpeo", + "Old_South_Arabian", + "Sarb", + "Old_Turkic", + "Orkh", + "Oriya", + "Orya", + "Osage", + "Osge", + "Osmanya", + "Osma", + "Pahawh_Hmong", + "Hmng", + "Palmyrene", + "Palm", + "Pau_Cin_Hau", + "Pauc", + "Phags_Pa", + "Phag", + "Phoenician", + "Phnx", + "Psalter_Pahlavi", + "Phlp", + "Rejang", + "Rjng", + "Runic", + "Runr", + "Samaritan", + "Samr", + "Saurashtra", + "Saur", + "Sharada", + "Shrd", + "Shavian", + "Shaw", + "Siddham", + "Sidd", + "SignWriting", + "Sgnw", + "Sinhala", + "Sinh", + "Sora_Sompeng", + "Sora", + "Soyombo", + "Soyo", + "Sundanese", + "Sund", + "Syloti_Nagri", + "Sylo", + "Syriac", + "Syrc", + "Tagalog", + "Tglg", + "Tagbanwa", + "Tagb", + "Tai_Le", + "Tale", + "Tai_Tham", + "Lana", + "Tai_Viet", + "Tavt", + "Takri", + "Takr", + "Tamil", + "Taml", + "Tangut", + "Tang", + "Telugu", + "Telu", + "Thaana", + "Thaa", + "Thai", + "Tibetan", + "Tibt", + "Tifinagh", + "Tfng", + "Tirhuta", + "Tirh", + "Ugaritic", + "Ugar", + "Vai", + "Vaii", + "Warang_Citi", + "Wara", + "Yi", + "Yiii", + "Zanabazar_Square", + "Zanb" + ] +}; +Array.prototype.push.apply(data.$LONE, data.General_Category); +data.gc = data.General_Category; +data.sc = data.Script_Extensions = data.scx = data.Script; + +var pp$9 = Parser.prototype; + +var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; +}; + +RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; +}; + +RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); +}; + +// If u flag is given, this returns the code point at the index (it combines a surrogate pair). +// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). +RegExpValidationState.prototype.at = function at (i) { + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + return (c << 10) + s.charCodeAt(i + 1) - 0x35FDC00 +}; + +RegExpValidationState.prototype.nextIndex = function nextIndex (i) { + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i); + if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return i + 1 + } + return i + 2 +}; + +RegExpValidationState.prototype.current = function current () { + return this.at(this.pos) +}; + +RegExpValidationState.prototype.lookahead = function lookahead () { + return this.at(this.nextIndex(this.pos)) +}; + +RegExpValidationState.prototype.advance = function advance () { + this.pos = this.nextIndex(this.pos); +}; + +RegExpValidationState.prototype.eat = function eat (ch) { + if (this.current() === ch) { + this.advance(); + return true + } + return false +}; + +function codePointToString$1(ch) { + if (ch <= 0xFFFF) { return String.fromCharCode(ch) } + ch -= 0x10000; + return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) +} + +/** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ +pp$9.validateRegExpFlags = function(state) { + var this$1 = this; + + var validFlags = state.validFlags; + var flags = state.flags; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this$1.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this$1.raise(state.start, "Duplicate regular expression flag"); + } + } +}; + +/** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ +pp$9.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern +pp$9.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction +pp$9.regexp_disjunction = function(state) { + var this$1 = this; + + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this$1.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative +pp$9.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term +pp$9.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion +pp$9.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier +pp$9.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix +pp$9.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) +}; +pp$9.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom +pp$9.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) +}; +pp$9.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false +}; +pp$9.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false +}; +pp$9.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom +pp$9.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier +pp$9.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter +pp$9.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false +}; +function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter +// But eat eager. +pp$9.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter +pp$9.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false +}; + +// GroupSpecifier[U] :: +// [empty] +// `?` GroupName[?U] +pp$9.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } +}; + +// GroupName[U] :: +// `<` RegExpIdentifierName[?U] `>` +// Note: this updates `state.lastStringValue` property with the eaten name. +pp$9.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false +}; + +// RegExpIdentifierName[U] :: +// RegExpIdentifierStart[?U] +// RegExpIdentifierName[?U] RegExpIdentifierPart[?U] +// Note: this updates `state.lastStringValue` property with the eaten name. +pp$9.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString$1(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString$1(state.lastIntValue); + } + return true + } + return false +}; + +// RegExpIdentifierStart[U] :: +// UnicodeIDStart +// `$` +// `_` +// `\` RegExpUnicodeEscapeSequence[?U] +pp$9.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var ch = state.current(); + state.advance(); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false +}; +function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ +} + +// RegExpIdentifierPart[U] :: +// UnicodeIDContinue +// `$` +// `_` +// `\` RegExpUnicodeEscapeSequence[?U] +// +// +pp$9.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var ch = state.current(); + state.advance(); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false +}; +function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape +pp$9.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false +}; +pp$9.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false +}; +pp$9.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape +pp$9.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) +}; +pp$9.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false +}; +pp$9.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape +pp$9.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter +pp$9.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false +}; +function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence +pp$9.regexp_eatRegExpUnicodeEscapeSequence = function(state) { + var start = state.pos; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + state.switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (state.switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false +}; +function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape +pp$9.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape +pp$9.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape +pp$9.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return true + } + + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + (ch === 0x50 /* P */ || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + if ( + state.eat(0x7B /* { */) && + this.regexp_eatUnicodePropertyValueExpression(state) && + state.eat(0x7D /* } */) + ) { + return true + } + state.raise("Invalid property name"); + } + + return false +}; +function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) +} + +// UnicodePropertyValueExpression :: +// UnicodePropertyName `=` UnicodePropertyValue +// LoneUnicodePropertyNameOrValue +pp$9.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return true + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); + return true + } + return false +}; +pp$9.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!data.hasOwnProperty(name) || data[name].indexOf(value) === -1) { + state.raise("Invalid property name"); + } +}; +pp$9.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (data.$LONE.indexOf(nameOrValue) === -1) { + state.raise("Invalid property name"); + } +}; + +// UnicodePropertyName :: +// UnicodePropertyNameCharacters +pp$9.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString$1(ch); + state.advance(); + } + return state.lastStringValue !== "" +}; +function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ +} + +// UnicodePropertyValue :: +// UnicodePropertyValueCharacters +pp$9.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString$1(ch); + state.advance(); + } + return state.lastStringValue !== "" +}; +function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) +} + +// LoneUnicodePropertyNameOrValue :: +// UnicodePropertyValueCharacters +pp$9.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass +pp$9.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + state.eat(0x5E /* ^ */); + this.regexp_classRanges(state); + if (state.eat(0x5D /* [ */)) { + return true + } + // Unreachable since it threw "unterminated regular expression" error before. + state.raise("Unterminated character class"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges +// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges +// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash +pp$9.regexp_classRanges = function(state) { + var this$1 = this; + + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this$1.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash +pp$9.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* [ */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape +pp$9.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter +pp$9.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence +pp$9.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits +pp$9.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start +}; +function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits +pp$9.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start +}; +function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) +} +function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence +// Allows only 0-377(octal) i.e. 0-255(decimal). +pp$9.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit +pp$9.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false +}; +function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit +// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence +pp$9.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true +}; + +// Object type used to represent tokens. Note that normally, tokens +// simply exist as properties on the parser object. This is only +// used for the onToken callback and the external tokenizer. + +var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } +}; + +// ## Tokenizer + +var pp$8 = Parser.prototype; + +// Move to the next token + +pp$8.next = function() { + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); +}; + +pp$8.getToken = function() { + this.next(); + return new Token(this) +}; + +// If we're in an ES6 environment, make parsers iterable +if (typeof Symbol !== "undefined") + { pp$8[Symbol.iterator] = function() { + var this$1 = this; + + return { + next: function () { + var token = this$1.getToken(); + return { + done: token.type === types.eof, + value: token + } + } + } + }; } + +// Toggle strict mode. Re-reads the next number or string to please +// pedantic tests (`"use strict"; 010;` should fail). + +pp$8.curContext = function() { + return this.context[this.context.length - 1] +}; + +// Read a single token, updating the parser object's token-related +// properties. + +pp$8.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } +}; + +pp$8.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) +}; + +pp$8.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xe000) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return (code << 10) + next - 0x35fdc00 +}; + +pp$8.skipBlockComment = function() { + var this$1 = this; + + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + lineBreakG.lastIndex = start; + var match; + while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { + ++this$1.curLine; + this$1.lineStart = match.index + match[0].length; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } +}; + +pp$8.skipLineComment = function(startSkip) { + var this$1 = this; + + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this$1.input.charCodeAt(++this$1.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } +}; + +// Called at the start of the parse and after every token. Skips +// whitespace and comments, and. + +pp$8.skipSpace = function() { + var this$1 = this; + + loop: while (this.pos < this.input.length) { + var ch = this$1.input.charCodeAt(this$1.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this$1.pos; + break + case 13: + if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { + ++this$1.pos; + } + case 10: case 8232: case 8233: + ++this$1.pos; + if (this$1.options.locations) { + ++this$1.curLine; + this$1.lineStart = this$1.pos; + } + break + case 47: // '/' + switch (this$1.input.charCodeAt(this$1.pos + 1)) { + case 42: // '*' + this$1.skipBlockComment(); + break + case 47: + this$1.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this$1.pos; + } else { + break loop + } + } + } +}; + +// Called at the end of every token. Sets `end`, `val`, and +// maintains `context` and `exprAllowed`, and skips the space after +// the token, so that the next one's `start` will point at the +// right position. + +pp$8.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); +}; + +// ### Token reading + +// This is the function that is called to fetch the next token. It +// is somewhat obscure, because it works in character codes rather +// than characters, and because operator parsing has been inlined +// into it. +// +// All in the name of speed. +// +pp$8.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types.ellipsis) + } else { + ++this.pos; + return this.finishToken(types.dot) + } +}; + +pp$8.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.slash, 1) +}; + +pp$8.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types.star : types.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(tokentype, size) +}; + +pp$8.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) +}; + +pp$8.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.bitwiseXOR, 1) +}; + +pp$8.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types.incDec, 2) + } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.plusMin, 1) +}; + +pp$8.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(types.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(ch); + case 46: return handle_dot(); + case 47: { + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + case 61: return handle_eq_sign(); + case 96: return read_template_characters(true); + case 123: + S.brace_counter++; + break; + case 125: + S.brace_counter--; + if (S.template_braces.length > 0 + && S.template_braces[S.template_braces.length - 1] === S.brace_counter) + return read_template_characters(false); + break; + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS(ch)) return token("punc", next()); + if (OPERATOR_CHARS(ch)) return read_operator(); + if (code == 92 || is_identifier_start(ch)) return read_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + } + + next_token.next = next; + next_token.peek = peek; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directive_stack[S.directive_stack.length - 1].push(directive); + + if (S.directives[directive] === undefined) { + S.directives[directive] = 1; + } else { + S.directives[directive]++; + } + }; + + next_token.push_directives_stack = function() { + S.directive_stack.push([]); + }; + + next_token.pop_directives_stack = function() { + var directives = S.directive_stack[S.directive_stack.length - 1]; + + for (var i = 0; i < directives.length; i++) { + S.directives[directives[i]]--; + } + + S.directive_stack.pop(); + }; + + next_token.has_directive = function(directive) { + return S.directives[directive] > 0; + }; + + return next_token; + +} + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "**=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var PRECEDENCE = (function(a, ret) { + for (var i = 0; i < a.length; ++i) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"], + ["**"] + ], + {} +); + +var ATOMIC_START_TOKEN = makePredicate([ "atom", "num", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + + options = defaults(options, { + bare_returns : false, + ecma : 8, + expression : false, + filename : null, + html5_comments : true, + module : false, + shebang : true, + strict : false, + toplevel : null, + }, true); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_async : -1, + in_generator : -1, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + } + + function peek() { return S.peeked || (S.peeked = S.input()); } + + function next() { + S.prev = S.token; + + if (!S.peeked) peek(); + S.token = S.peeked; + S.peeked = null; + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + } + + function prev() { + return S.prev; + } + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + } + + function token_error(token, msg) { + croak(msg, token.line, token.col); + } + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + } + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + } + + function expect(punc) { return expect_token("punc", punc); } + + function has_newline_before(token) { + return token.nlb || !all(token.comments_before, function(comment) { + return !comment.nlb; + }); + } + + function can_insert_semicolon() { + return !options.strict + && (is("eof") || is("punc", "}") || has_newline_before(S.token)); + } + + function is_in_generator() { + return S.in_generator === S.in_function; + } + + function is_in_async() { + return S.in_async === S.in_function; + } + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + } + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + } + + function embed_tokens(parser) { + return function() { + var start = S.token; + var expr = parser.apply(null, arguments); + var end = prev(); + expr.start = start; + expr.end = end; + return expr; + }; + } + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + } + + var statement = embed_tokens(function(is_export_default, is_for_body, is_if_body) { + handle_regexp(); + switch (S.token.type) { + case "string": + if (S.in_directives) { + var token = peek(); + if (S.token.raw.indexOf("\\") == -1 + && (is_token(token, "punc", ";") + || is_token(token, "punc", "}") + || has_newline_before(token) + || is_token(token, "eof"))) { + S.input.add_directive(S.token.value); + } else { + S.in_directives = false; + } + } + var dir = S.in_directives, stat = simple_statement(); + return dir && stat.body instanceof AST_String ? new AST_Directive(stat.body) : stat; + case "template_head": + case "num": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + if (S.token.value == "async" && is_token(peek(), "keyword", "function")) { + next(); + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, true, is_export_default); + } + if (S.token.value == "import" && !is_token(peek(), "punc", "(")) { + next(); + var node = import_(); + semicolon(); + return node; + } + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesised(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesised(), + body : in_loop(function() { return statement(false, true); }) + }); + + case "for": + next(); + return for_(); + + case "class": + next(); + if (is_for_body) { + croak("classes are not allowed as the body of a loop"); + } + if (is_if_body) { + croak("classes are not allowed as the body of an if"); + } + return class_(AST_DefClass); + + case "function": + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, false, is_export_default); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(true); + semicolon(); + } + return new AST_Return({ + value: value + }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + next(); + if (has_newline_before(S.token)) + croak("Illegal newline after 'throw'"); + var value = expression(true); + semicolon(); + return new AST_Throw({ + value: value + }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "let": + next(); + var node = let_(); + semicolon(); + return node; + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + + case "export": + if (!is_token(peek(), "punc", "(")) { + next(); + var node = export_(); + if (is("punc", ";")) semicolon(); + return node; + } + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (label.name === "await" && is_in_async()) { + token_error(S.prev, "await cannot be used as label inside async function"); + } + if (find_if(function(l) { return l.name == label.name; }, S.labels)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref) { + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + } + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + } + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = find_if(function(l) { return l.name == label.name; }, S.labels); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + } + + function for_() { + var for_await_error = "`for await` invalid in this context"; + var await_tok = S.token; + if (await_tok.type == "name" && await_tok.value == "await") { + if (!is_in_async()) { + token_error(await_tok, for_await_error); + } + next(); + } else { + await_tok = false; + } + expect("("); + var init = null; + if (!is("punc", ";")) { + init = + is("keyword", "var") ? (next(), var_(true)) : + is("keyword", "let") ? (next(), let_(true)) : + is("keyword", "const") ? (next(), const_(true)) : + expression(true, true); + var is_in = is("operator", "in"); + var is_of = is("name", "of"); + if (await_tok && !is_of) { + token_error(await_tok, for_await_error); + } + if (is_in || is_of) { + if (init instanceof AST_Definitions) { + if (init.definitions.length > 1) + token_error(init.start, "Only one variable declaration allowed in for..in loop"); + } else if (!(is_assignable(init) || (init = to_destructuring(init)) instanceof AST_Destructuring)) { + token_error(init.start, "Invalid left-hand side in for..in loop"); + } + next(); + if (is_in) { + return for_in(init); + } else { + return for_of(init, !!await_tok); + } + } + } else if (await_tok) { + token_error(await_tok, for_await_error); + } + return regular_for(init); + } + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_of(init, is_await) { + var lhs = init instanceof AST_Definitions ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForOf({ + await : is_await, + init : init, + name : lhs, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_in(init) { + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + var arrow_function = function(start, argnames, is_async) { + if (has_newline_before(S.token)) { + croak("Unexpected newline before arrow (=>)"); + } + + expect_token("arrow", "=>"); + + var body = _function_body(is("punc", "{"), false, is_async); + + var end = + body instanceof Array && body.length ? body[body.length - 1].end : + body instanceof Array ? start : + body.end; + + return new AST_Arrow({ + start : start, + end : end, + async : is_async, + argnames : argnames, + body : body + }); + }; + + var function_ = function(ctor, is_generator_property, is_async, is_export_default) { + var start = S.token; + + var in_statement = ctor === AST_Defun; + var is_generator = is("operator", "*"); + if (is_generator) { + next(); + } + + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) { + if (is_export_default) { + ctor = AST_Function; + } else { + unexpected(); + } + } + + if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration)) + unexpected(prev()); + + var args = []; + var body = _function_body(true, is_generator || is_generator_property, is_async, name, args); + return new ctor({ + start : args.start, + end : body.end, + is_generator: is_generator, + async : is_async, + name : name, + argnames: args, + body : body + }); + }; + + function track_used_binding_identifiers(is_parameter, strict) { + var parameters = {}; + var duplicate = false; + var default_assignment = false; + var spread = false; + var strict_mode = !!strict; + var tracker = { + add_parameter: function(token) { + if (parameters["$" + token.value] !== undefined) { + if (duplicate === false) { + duplicate = token; + } + tracker.check_strict(); + } else { + parameters["$" + token.value] = true; + if (is_parameter) { + switch (token.value) { + case "arguments": + case "eval": + case "yield": + if (strict_mode) { + token_error(token, "Unexpected " + token.value + " identifier as parameter inside strict mode"); + } + break; + default: + if (RESERVED_WORDS(token.value)) { + unexpected(); + } + } + } + } + }, + mark_default_assignment: function(token) { + if (default_assignment === false) { + default_assignment = token; + } + }, + mark_spread: function(token) { + if (spread === false) { + spread = token; + } + }, + mark_strict_mode: function() { + strict_mode = true; + }, + is_strict: function() { + return default_assignment !== false || spread !== false || strict_mode; + }, + check_strict: function() { + if (tracker.is_strict() && duplicate !== false) { + token_error(duplicate, "Parameter " + duplicate.value + " was used already"); + } + } + }; + + return tracker; + } + + function parameters(params) { + var start = S.token; + var used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); + + expect("("); + + while (!is("punc", ")")) { + var param = parameter(used_parameters); + params.push(param); + + if (!is("punc", ")")) { + expect(","); + if (is("punc", ")") && options.ecma < 8) unexpected(); + } + + if (param instanceof AST_Expansion) { + break; + } + } + + next(); + } + + function parameter(used_parameters, symbol_type) { + var param; + var expand = false; + if (used_parameters === undefined) { + used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); + } + if (is("expand", "...")) { + expand = S.token; + used_parameters.mark_spread(S.token); + next(); + } + param = binding_element(used_parameters, symbol_type); + + if (is("operator", "=") && expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + param = new AST_DefaultAssign({ + start: param.start, + left: param, + operator: "=", + right: expression(false), + end: S.token + }); + } + + if (expand !== false) { + if (!is("punc", ")")) { + unexpected(); + } + param = new AST_Expansion({ + start: expand, + expression: param, + end: expand + }); + } + used_parameters.check_strict(); + + return param; + } + + function binding_element(used_parameters, symbol_type) { + var elements = []; + var first = true; + var is_expand = false; + var expand_token; + var first_token = S.token; + if (used_parameters === undefined) { + used_parameters = track_used_binding_identifiers(false, S.input.has_directive("use strict")); + } + symbol_type = symbol_type === undefined ? AST_SymbolFunarg : symbol_type; + if (is("punc", "[")) { + next(); + while (!is("punc", "]")) { + if (first) { + first = false; + } else { + expect(","); + } + + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("punc")) { + switch (S.token.value) { + case ",": + elements.push(new AST_Hole({ + start: S.token, + end: S.token + })); + continue; + case "]": // Trailing comma after last element + break; + case "[": + case "{": + elements.push(binding_element(used_parameters, symbol_type)); + break; + default: + unexpected(); + } + } else if (is("name")) { + used_parameters.add_parameter(S.token); + elements.push(as_symbol(symbol_type)); + } else { + croak("Invalid function parameter"); + } + if (is("operator", "=") && is_expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1] = new AST_DefaultAssign({ + start: elements[elements.length - 1].start, + left: elements[elements.length - 1], + operator: "=", + right: expression(false), + end: S.token + }); + } + if (is_expand) { + if (!is("punc", "]")) { + croak("Rest element must be last element"); + } + elements[elements.length - 1] = new AST_Expansion({ + start: expand_token, + expression: elements[elements.length - 1], + end: expand_token + }); + } + } + expect("]"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: true, + end: prev() + }); + } else if (is("punc", "{")) { + next(); + while (!is("punc", "}")) { + if (first) { + first = false; + } else { + expect(","); + } + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("name") && (is_token(peek(), "punc") || is_token(peek(), "operator")) && [",", "}", "="].indexOf(peek().value) !== -1) { + used_parameters.add_parameter(S.token); + var start = prev(); + var value = as_symbol(symbol_type); + if (is_expand) { + elements.push(new AST_Expansion({ + start: expand_token, + expression: value, + end: value.end, + })); + } else { + elements.push(new AST_ObjectKeyVal({ + start: start, + key: value.name, + value: value, + end: value.end, + })); + } + } else if (is("punc", "}")) { + continue; // Allow trailing hole + } else { + var property_token = S.token; + var property = as_property_name(); + if (property === null) { + unexpected(prev()); + } else if (prev().type === "name" && !is("punc", ":")) { + elements.push(new AST_ObjectKeyVal({ + start: prev(), + key: property, + value: new symbol_type({ + start: prev(), + name: property, + end: prev() + }), + end: prev() + })); + } else { + expect(":"); + elements.push(new AST_ObjectKeyVal({ + start: property_token, + quote: property_token.quote, + key: property, + value: binding_element(used_parameters, symbol_type), + end: prev() + })); + } + } + if (is_expand) { + if (!is("punc", "}")) { + croak("Rest element must be last element"); + } + } else if (is("operator", "=")) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1].value = new AST_DefaultAssign({ + start: elements[elements.length - 1].value.start, + left: elements[elements.length - 1].value, + operator: "=", + right: expression(false), + end: S.token + }); + } + } + expect("}"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: false, + end: prev() + }); + } else if (is("name")) { + used_parameters.add_parameter(S.token); + return as_symbol(symbol_type); + } else { + croak("Invalid function parameter"); + } + } + + function params_or_seq_(allow_arrows, maybe_sequence) { + var spread_token; + var invalid_sequence; + var trailing_comma; + var a = []; + expect("("); + while (!is("punc", ")")) { + if (spread_token) unexpected(spread_token); + if (is("expand", "...")) { + spread_token = S.token; + if (maybe_sequence) invalid_sequence = S.token; + next(); + a.push(new AST_Expansion({ + start: prev(), + expression: expression(), + end: S.token, + })); + } else { + a.push(expression()); + } + if (!is("punc", ")")) { + expect(","); + if (is("punc", ")")) { + if (options.ecma < 8) unexpected(); + trailing_comma = prev(); + if (maybe_sequence) invalid_sequence = trailing_comma; + } + } + } + expect(")"); + if (allow_arrows && is("arrow", "=>")) { + if (spread_token && trailing_comma) unexpected(trailing_comma); + } else if (invalid_sequence) { + unexpected(invalid_sequence); + } + return a; + } + + function _function_body(block, generator, is_async, name, args) { + var loop = S.in_loop; + var labels = S.labels; + var current_generator = S.in_generator; + var current_async = S.in_async; + ++S.in_function; + if (generator) + S.in_generator = S.in_function; + if (is_async) + S.in_async = S.in_function; + if (args) parameters(args); + if (block) + S.in_directives = true; + S.in_loop = 0; + S.labels = []; + if (block) { + S.input.push_directives_stack(); + var a = block_(); + if (name) _verify_symbol(name); + if (args) args.forEach(_verify_symbol); + S.input.pop_directives_stack(); + } else { + var a = expression(false); + } + --S.in_function; + S.in_loop = loop; + S.labels = labels; + S.in_generator = current_generator; + S.in_async = current_async; + return a; + } + + function _await_expression() { + // Previous token must be "await" and not be interpreted as an identifier + if (!is_in_async()) { + croak("Unexpected await expression outside async function", + S.prev.line, S.prev.col, S.prev.pos); + } + // the await expression is parsed as a unary expression in Babel + return new AST_Await({ + start: prev(), + end: S.token, + expression : maybe_unary(true), + }); + } + + function _yield_expression() { + // Previous token must be keyword yield and not be interpret as an identifier + if (!is_in_generator()) { + croak("Unexpected yield expression outside generator function", + S.prev.line, S.prev.col, S.prev.pos); + } + var start = S.token; + var star = false; + var has_expression = true; + + // Attempt to get expression or star (and then the mandatory expression) + // behind yield on the same line. + // + // If nothing follows on the same line of the yieldExpression, + // it should default to the value `undefined` for yield to return. + // In that case, the `undefined` stored as `null` in ast. + // + // Note 1: It isn't allowed for yield* to close without an expression + // Note 2: If there is a nlb between yield and star, it is interpret as + // yield * + if (can_insert_semicolon() || + (is("punc") && PUNC_AFTER_EXPRESSION(S.token.value))) { + has_expression = false; + + } else if (is("operator", "*")) { + star = true; + next(); + } + + return new AST_Yield({ + start : start, + is_star : star, + expression : has_expression ? expression() : null, + end : prev() + }); + } + + function if_() { + var cond = parenthesised(), body = statement(false, false, true), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(false, false, true); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + } + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + } + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + } + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + if (is("punc", "{")) { + var name = null; + } else { + expect("("); + var name = parameter(undefined, AST_SymbolCatch); + expect(")"); + } + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + } + + function vardefs(no_in, kind) { + var a = []; + var def; + for (;;) { + var sym_type = + kind === "var" ? AST_SymbolVar : + kind === "const" ? AST_SymbolConst : + kind === "let" ? AST_SymbolLet : null; + if (is("punc", "{") || is("punc", "[")) { + def = new AST_VarDef({ + start: S.token, + name: binding_element(undefined ,sym_type), + value: is("operator", "=") ? (expect_token("operator", "="), expression(false, no_in)) : null, + end: prev() + }); + } else { + def = new AST_VarDef({ + start : S.token, + name : as_symbol(sym_type), + value : is("operator", "=") + ? (next(), expression(false, no_in)) + : !no_in && kind === "const" + ? croak("Missing initializer in const declaration") : null, + end : prev() + }); + if (def.name.name == "import") croak("Unexpected token: import"); + } + a.push(def); + if (!is("punc", ",")) + break; + next(); + } + return a; + } + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, "var"), + end : prev() + }); + }; + + var let_ = function(no_in) { + return new AST_Let({ + start : prev(), + definitions : vardefs(no_in, "let"), + end : prev() + }); + }; + + var const_ = function(no_in) { + return new AST_Const({ + start : prev(), + definitions : vardefs(no_in, "const"), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + if (is("punc", ".")) { + next(); + expect_token("name", "target"); + return subscripts(new AST_NewTarget({ + start : start, + end : prev() + }), allow_calls); + } + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")", options.ecma >= 8); + } else { + args = []; + } + var call = new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }); + mark_pure(call); + return subscripts(call, allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + break; + case "regexp": + ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + } + next(); + return ret; + } + + function to_fun_args(ex, _, __, default_seen_above) { + var insert_default = function(ex, default_value) { + if (default_value) { + return new AST_DefaultAssign({ + start: ex.start, + left: ex, + operator: "=", + right: default_value, + end: default_value.end + }); + } + return ex; + }; + if (ex instanceof AST_Object) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: false, + names: ex.properties.map(to_fun_args) + }), default_seen_above); + } else if (ex instanceof AST_ObjectKeyVal) { + ex.value = to_fun_args(ex.value, 0, [ex.key]); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Hole) { + return ex; + } else if (ex instanceof AST_Destructuring) { + ex.names = ex.names.map(to_fun_args); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_SymbolRef) { + return insert_default(new AST_SymbolFunarg({ + name: ex.name, + start: ex.start, + end: ex.end + }), default_seen_above); + } else if (ex instanceof AST_Expansion) { + ex.expression = to_fun_args(ex.expression); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Array) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: true, + names: ex.elements.map(to_fun_args) + }), default_seen_above); + } else if (ex instanceof AST_Assign) { + return insert_default(to_fun_args(ex.left, undefined, undefined, ex.right), default_seen_above); + } else if (ex instanceof AST_DefaultAssign) { + ex.left = to_fun_args(ex.left, 0, [ex.left]); + return ex; + } else { + croak("Invalid function parameter", ex.start.line, ex.start.col); + } + } + + var expr_atom = function(allow_calls, allow_arrows) { + if (is("operator", "new")) { + return new_(allow_calls); + } + var start = S.token; + var peeked; + var async = is("name", "async") + && (peeked = peek()).value != "[" + && peeked.type != "arrow" + && as_atom_node(); + if (is("punc")) { + switch (S.token.value) { + case "(": + if (async && !allow_calls) break; + var exprs = params_or_seq_(allow_arrows, !async); + if (allow_arrows && is("arrow", "=>")) { + return arrow_function(start, exprs.map(to_fun_args), !!async); + } + var ex = async ? new AST_Call({ + expression: async, + args: exprs + }) : exprs.length == 1 ? exprs[0] : new AST_Sequence({ + expressions: exprs + }); + if (ex.start) { + var len = start.comments_before.length; + [].unshift.apply(ex.start.comments_before, start.comments_before); + start.comments_before = ex.start.comments_before; + start.comments_before_length = len; + if (len == 0 && start.comments_before.length > 0) { + var comment = start.comments_before[0]; + if (!comment.nlb) { + comment.nlb = start.nlb; + start.nlb = false; + } + } + start.comments_after = ex.start.comments_after; + } + ex.start = start; + var end = prev(); + if (ex.end) { + end.comments_before = ex.end.comments_before; + [].push.apply(ex.end.comments_after, end.comments_after); + end.comments_after = ex.end.comments_after; + } + ex.end = end; + if (ex instanceof AST_Call) mark_pure(ex); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_or_destructuring_(), allow_calls); + } + if (!async) unexpected(); + } + if (allow_arrows && is("name") && is_token(peek(), "arrow")) { + var param = new AST_SymbolFunarg({ + name: S.token.value, + start: start, + end: start, + }); + next(); + return arrow_function(start, [param], !!async); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function, false, !!async); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (async) return subscripts(async, allow_calls); + if (is("keyword", "class")) { + next(); + var cls = class_(AST_ClassExpression); + cls.start = start; + cls.end = prev(); + return subscripts(cls, allow_calls); + } + if (is("template_head")) { + return subscripts(template_string(false), allow_calls); + } + if (ATOMIC_START_TOKEN(S.token.type)) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function template_string(tagged) { + var segments = [], start = S.token; + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: S.token.raw, + value: S.token.value, + end: S.token + })); + while (S.token.end === false) { + next(); + handle_regexp(); + segments.push(expression(true)); + + if (!is_token("template_substitution")) { + unexpected(); + } + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: S.token.raw, + value: S.token.value, + end: S.token + })); + } + next(); + + return new AST_TemplateString({ + start: start, + segments: segments, + end: S.token + }); + } + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else if (is("expand", "...")) { + next(); + a.push(new AST_Expansion({start: prev(), expression: expression(),end: S.token})); + } else { + a.push(expression(false)); + } + } + next(); + return a; + } + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens(function(is_generator, is_async) { + return function_(AST_Accessor, is_generator, is_async); + }); + + var object_or_destructuring_ = embed_tokens(function object_or_destructuring_() { + var start = S.token, first = true, a = []; + expect("{"); + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + + start = S.token; + if (start.type == "expand") { + next(); + a.push(new AST_Expansion({ + start: start, + expression: expression(false), + end: prev(), + })); + continue; + } + + var name = as_property_name(); + var value; + + // Check property and fetch value + if (!is("punc", ":")) { + var concise = concise_method_or_getset(name, start); + if (concise) { + a.push(concise); + continue; + } + + value = new AST_SymbolRef({ + start: prev(), + name: name, + end: prev() + }); + } else if (name === null) { + unexpected(prev()); + } else { + next(); // `:` - see first condition + value = expression(false); + } + + // Check for default value and alter value accordingly if necessary + if (is("operator", "=")) { + next(); + value = new AST_Assign({ + start: start, + left: value, + operator: "=", + right: expression(false), + end: prev() + }); + } + + // Create property + a.push(new AST_ObjectKeyVal({ + start: start, + quote: start.quote, + key: name instanceof AST_Node ? name : "" + name, + value: value, + end: prev() + })); + } + next(); + return new AST_Object({ properties: a }); + }); + + function class_(KindOfClass) { + var start, method, class_name, extends_, a = []; + + S.input.push_directives_stack(); // Push directive stack, but not scope stack + S.input.add_directive("use strict"); + + if (S.token.type == "name" && S.token.value != "extends") { + class_name = as_symbol(KindOfClass === AST_DefClass ? AST_SymbolDefClass : AST_SymbolClass); + } + + if (KindOfClass === AST_DefClass && !class_name) { + unexpected(); + } + + if (S.token.value == "extends") { + next(); + extends_ = expression(true); + } + + expect("{"); + + if (is("punc", ";")) { next(); } // Leading semicolons are okay in class bodies. + while (!is("punc", "}")) { + start = S.token; + method = concise_method_or_getset(as_property_name(), start, true); + if (!method) { unexpected(); } + a.push(method); + if (is("punc", ";")) { next(); } + } + + S.input.pop_directives_stack(); + + next(); + + return new KindOfClass({ + start: start, + name: class_name, + extends: extends_, + properties: a, + end: prev(), + }); + } + + function concise_method_or_getset(name, start, is_class) { + var get_ast = function(name, token) { + if (typeof name === "string" || typeof name === "number") { + return new AST_SymbolMethod({ + start: token, + name: "" + name, + end: prev() + }); + } else if (name === null) { + unexpected(); + } + return name; + }; + var is_async = false; + var is_static = false; + var is_generator = false; + var property_token = start; + if (is_class && name === "static" && !is("punc", "(")) { + is_static = true; + property_token = S.token; + name = as_property_name(); + } + if (name === "async" && !is("punc", "(") && !is("punc", ",") && !is("punc", "}")) { + is_async = true; + property_token = S.token; + name = as_property_name(); + } + if (name === null) { + is_generator = true; + property_token = S.token; + name = as_property_name(); + if (name === null) { + unexpected(); + } + } + if (is("punc", "(")) { + name = get_ast(name, start); + var node = new AST_ConciseMethod({ + start : start, + static : is_static, + is_generator: is_generator, + async : is_async, + key : name, + quote : name instanceof AST_SymbolMethod ? + property_token.quote : undefined, + value : create_accessor(is_generator, is_async), + end : prev() + }); + return node; + } + property_token = S.token; + if (name == "get") { + if (!is("punc") || is("punc", "[")) { + name = get_ast(as_property_name(), start); + return new AST_ObjectGetter({ + start : start, + static: is_static, + key : name, + quote : name instanceof AST_SymbolMethod ? + property_token.quote : undefined, + value : create_accessor(), + end : prev() + }); + } + } else if (name == "set") { + if (!is("punc") || is("punc", "[")) { + name = get_ast(as_property_name(), start); + return new AST_ObjectSetter({ + start : start, + static: is_static, + key : name, + quote : name instanceof AST_SymbolMethod ? + property_token.quote : undefined, + value : create_accessor(), + end : prev() + }); + } + } + } + + function import_() { + var start = prev(); + var imported_name; + var imported_names; + if (is("name")) { + imported_name = as_symbol(AST_SymbolImport); + } + + if (is("punc", ",")) { + next(); + } + + imported_names = map_names(true); + + if (imported_names || imported_name) { + expect_token("name", "from"); + } + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + return new AST_Import({ + start: start, + imported_name: imported_name, + imported_names: imported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + end: S.token, + }); + } + + function map_name(is_import) { + function make_symbol(type) { + return new type({ + name: as_property_name(), + start: prev(), + end: prev() + }); + } + + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var name; + + if (is_import) { + foreign_name = make_symbol(foreign_type); + } else { + name = make_symbol(type); + } + if (is("name", "as")) { + next(); // The "as" word + if (is_import) { + name = make_symbol(type); + } else { + foreign_name = make_symbol(foreign_type); + } + } else if (is_import) { + name = new type(foreign_name); + } else { + foreign_name = new foreign_type(name); + } + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: prev(), + }); + } + + function map_nameAsterisk(is_import, name) { + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var end = prev(); + + name = name || new type({ + name: "*", + start: start, + end: end, + }); + + foreign_name = new foreign_type({ + name: "*", + start: start, + end: end, + }); + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: end, + }); + } + + function map_names(is_import) { + var names; + if (is("punc", "{")) { + next(); + names = []; + while (!is("punc", "}")) { + names.push(map_name(is_import)); + if (is("punc", ",")) { + next(); + } + } + next(); + } else if (is("operator", "*")) { + var name; + next(); + if (is_import && is("name", "as")) { + next(); // The "as" word + name = as_symbol(is_import ? AST_SymbolImport : AST_SymbolExportForeign); + } + names = [map_nameAsterisk(is_import, name)]; + } + return names; + } + + function export_() { + var start = S.token; + var is_default; + var exported_names; + + if (is("keyword", "default")) { + is_default = true; + next(); + } else if (exported_names = map_names(false)) { + if (is("name", "from")) { + next(); + + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + end: prev(), + }); + } else { + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + end: prev(), + }); + } + } + + var node; + var exported_value; + var exported_definition; + if (is("punc", "{") + || is_default + && (is("keyword", "class") || is("keyword", "function")) + && is_token(peek(), "punc")) { + exported_value = expression(false); + semicolon(); + } else if ((node = statement(is_default)) instanceof AST_Definitions && is_default) { + unexpected(node.start); + } else if (node instanceof AST_Definitions || node instanceof AST_Lambda || node instanceof AST_DefClass) { + exported_definition = node; + } else if (node instanceof AST_SimpleStatement) { + exported_value = node.body; + } else { + unexpected(node.start); + } + + return new AST_Export({ + start: start, + is_default: is_default, + exported_value: exported_value, + exported_definition: exported_definition, + end: prev(), + }); + } + + function as_property_name() { + var tmp = S.token; + switch (tmp.type) { + case "punc": + if (tmp.value === "[") { + next(); + var ex = expression(false); + expect("]"); + return ex; + } else unexpected(tmp); + case "operator": + if (tmp.value === "*") { + next(); + return null; + } + if (["delete", "in", "instanceof", "new", "typeof", "void"].indexOf(tmp.value) === -1) { + unexpected(tmp); + } + case "name": + if (tmp.value == "yield") { + if (is_in_generator()) { + token_error(tmp, "Yield cannot be used as identifier inside generators"); + } else if (!is_token(peek(), "punc", ":") + && !is_token(peek(), "punc", "(") + && S.input.has_directive("use strict")) { + token_error(tmp, "Unexpected yield identifier inside strict mode"); + } + } + case "string": + case "num": + case "keyword": + case "atom": + next(); + return tmp.value; + default: + unexpected(tmp); + } + } + + function as_name() { + var tmp = S.token; + if (tmp.type != "name") unexpected(); + next(); + return tmp.value; + } + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : + name == "super" ? AST_Super : + type)({ + name : String(name), + start : S.token, + end : S.token + }); + } + + function _verify_symbol(sym) { + var name = sym.name; + if (is_in_generator() && name == "yield") { + token_error(sym.start, "Yield cannot be used as identifier inside generators"); + } + if (S.input.has_directive("use strict")) { + if (name == "yield") { + token_error(sym.start, "Unexpected yield identifier inside strict mode"); + } + if (sym instanceof AST_SymbolDeclaration && (name == "arguments" || name == "eval")) { + token_error(sym.start, "Unexpected " + name + " in strict mode"); + } + } + } + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + _verify_symbol(sym); + next(); + return sym; + } + + function mark_pure(call) { + var start = call.start; + var comments = start.comments_before; + var i = HOP(start, "comments_before_length") ? start.comments_before_length : comments.length; + while (--i >= 0) { + var comment = comments[i]; + if (/[@#]__PURE__/.test(comment.value)) { + call.pure = comment; + break; + } + } + } + + var subscripts = function(expr, allow_calls) { + var start = expr.start; + if (is("punc", ".")) { + next(); + return subscripts(new AST_Dot({ + start : start, + expression : expr, + property : as_name(), + end : prev() + }), allow_calls); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return subscripts(new AST_Sub({ + start : start, + expression : expr, + property : prop, + end : prev() + }), allow_calls); + } + if (allow_calls && is("punc", "(")) { + next(); + var call = new AST_Call({ + start : start, + expression : expr, + args : call_args(), + end : prev() + }); + mark_pure(call); + return subscripts(call, true); + } + if (is("template_head")) { + return subscripts(new AST_PrefixedTemplateString({ + start: start, + prefix: expr, + template_string: template_string(true), + end: prev() + }), allow_calls); + } + return expr; + }; + + var call_args = embed_tokens(function _call_args() { + var args = []; + while (!is("punc", ")")) { + if (is("expand", "...")) { + next(); + args.push(new AST_Expansion({ + start: prev(), + expression: expression(false), + end: prev() + })); + } else { + args.push(expression(false)); + } + if (!is("punc", ")")) { + expect(","); + if (is("punc", ")") && options.ecma < 8) unexpected(); + } + } + next(); + return args; + }); + + var maybe_unary = function(allow_calls, allow_arrows) { + var start = S.token; + if (start.type == "name" && start.value == "await") { + if (is_in_async()) { + next(); + return _await_expression(); + } else if (S.input.has_directive("use strict")) { + token_error(S.token, "Unexpected await identifier inside strict mode"); + } + } + if (is("operator") && UNARY_PREFIX(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls, allow_arrows); + while (is("operator") && UNARY_POSTFIX(S.token.value) && !has_newline_before(S.token)) { + if (val instanceof AST_Arrow) unexpected(); + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, token, expr) { + var op = token.value; + switch (op) { + case "++": + case "--": + if (!is_assignable(expr)) + croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); + break; + case "delete": + if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict")) + croak("Calling delete on expression not allowed in strict mode", expr.start.line, expr.start.col, expr.start.pos); + break; + } + return new ctor({ operator: op, expression: expr }); + } + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + if (op == "**" && left instanceof AST_UnaryPrefix + /* unary token in front not allowed - parenthesis required */ + && !is_token(left.start, "punc", "(") + && left.operator !== "--" && left.operator !== "++") + unexpected(left.start); + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && (prec > min_prec || (op === "**" && min_prec === prec))) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true, true), 0, no_in); + } + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; + } + + function to_destructuring(node) { + if (node instanceof AST_Object) { + node = new AST_Destructuring({ + start: node.start, + names: node.properties.map(to_destructuring), + is_array: false, + end: node.end + }); + } else if (node instanceof AST_Array) { + var names = []; + + for (var i = 0; i < node.elements.length; i++) { + // Only allow expansion as last element + if (node.elements[i] instanceof AST_Expansion) { + if (i + 1 !== node.elements.length) { + token_error(node.elements[i].start, "Spread must the be last element in destructuring array"); + } + node.elements[i].expression = to_destructuring(node.elements[i].expression); + } + + names.push(to_destructuring(node.elements[i])); + } + + node = new AST_Destructuring({ + start: node.start, + names: names, + is_array: true, + end: node.end + }); + } else if (node instanceof AST_ObjectProperty) { + node.value = to_destructuring(node.value); + } else if (node instanceof AST_Assign) { + node = new AST_DefaultAssign({ + start: node.start, + left: node.left, + operator: "=", + right: node.right, + end: node.end + }); + } + return node; + } + + // In ES6, AssignmentExpression can also be an ArrowFunction + var maybe_assign = function(no_in) { + handle_regexp(); + var start = S.token; + + if (start.type == "name" && start.value == "yield") { + if (is_in_generator()) { + next(); + return _yield_expression(); + } else if (S.input.has_directive("use strict")) { + token_error(S.token, "Unexpected yield identifier inside strict mode"); + } + } + + var left = maybe_conditional(no_in); + var val = S.token.value; + + if (is("operator") && ASSIGNMENT(val)) { + if (is_assignable(left) || (left = to_destructuring(left)) instanceof AST_Destructuring) { + next(); + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = function(commas, no_in) { + var start = S.token; + var exprs = []; + while (true) { + exprs.push(maybe_assign(no_in)); + if (!commas || !is("punc", ",")) break; + next(); + commas = true; + } + return exprs.length == 1 ? exprs[0] : new AST_Sequence({ + start : start, + expressions : exprs, + end : peek() + }); + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + } + + if (options.expression) { + return expression(true); + } + + return (function() { + var start = S.token; + var body = []; + S.input.push_directives_stack(); + if (options.module) S.input.add_directive("use strict"); + while (!is("eof")) + body.push(statement()); + S.input.pop_directives_stack(); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + })(); + +} +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +function SymbolDef(scope, orig, init) { + this.name = orig.name; + this.orig = [ orig ]; + this.init = init; + this.eliminated = 0; + this.scope = scope; + this.references = []; + this.replaced = 0; + this.global = false; + this.export = false; + this.mangled_name = null; + this.undeclared = false; + this.id = SymbolDef.next_id++; +} + +SymbolDef.next_id = 1; + +var MASK_EXPORT_DONT_MANGLE = 1 << 0; +var MASK_EXPORT_WANT_MANGLE = 1 << 1; + +SymbolDef.prototype = { + unmangleable: function(options) { + if (!options) options = {}; + + return this.global && !options.toplevel + || (this.export & MASK_EXPORT_DONT_MANGLE) + || this.undeclared + || !options.eval && this.scope.pinned() + || (this.orig[0] instanceof AST_SymbolLambda + || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name) + || this.orig[0] instanceof AST_SymbolMethod + || (this.orig[0] instanceof AST_SymbolClass + || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name); + }, + mangle: function(options) { + var cache = options.cache && options.cache.props; + if (this.global && cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } else if (!this.mangled_name && !this.unmangleable(options)) { + var s = this.scope; + var sym = this.orig[0]; + if (options.ie8 && sym instanceof AST_SymbolLambda) + s = s.parent_scope; + var def; + if (def = this.redefined()) { + this.mangled_name = def.mangled_name || def.name; + } else + this.mangled_name = s.next_mangled(options, this); + if (this.global && cache) { + cache.set(this.name, this.mangled_name); + } + } + }, + redefined: function() { + return this.defun && this.defun.variables.get(this.name); + } +}; + +AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) { + options = defaults(options, { + cache: null, + ie8: false, + safari10: false, + }); + + // pass 1: setup scope chaining and handle definitions + var self = this; + var scope = self.parent_scope = null; + var labels = new Dictionary(); + var defun = null; + var in_destructuring = null; + var for_scopes = []; + var tw = new TreeWalker(function(node, descend) { + if (node.is_block_scope()) { + var save_scope = scope; + node.block_scope = scope = new AST_Scope(node); + scope.init_scope_vars(save_scope); + if (!(node instanceof AST_Scope)) { + scope.uses_with = save_scope.uses_with; + scope.uses_eval = save_scope.uses_eval; + scope.directives = save_scope.directives; + } + if (options.safari10) { + if (node instanceof AST_For || node instanceof AST_ForIn) { + for_scopes.push(scope); + } + } + descend(); + scope = save_scope; + return true; + } + if (node instanceof AST_Destructuring) { + in_destructuring = node; // These don't nest + descend(); + in_destructuring = null; + return true; + } + if (node instanceof AST_Scope) { + node.init_scope_vars(scope); + var save_scope = scope; + var save_defun = defun; + var save_labels = labels; + defun = scope = node; + labels = new Dictionary(); + descend(); + scope = save_scope; + defun = save_defun; + labels = save_labels; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) { + throw new Error(string_template("Label {name} defined twice", l)); + } + labels.set(l.name, l); + descend(); + labels.del(l.name); + return true; // no descend again + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolLambda) { + defun.def_function(node, node.name == "arguments" ? undefined : defun); + } else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + mark_export((node.scope = defun.parent_scope.get_defun_scope()).def_function(node, defun), 1); + } else if (node instanceof AST_SymbolClass) { + mark_export(defun.def_variable(node, defun), 1); + } else if (node instanceof AST_SymbolImport) { + scope.def_variable(node); + } else if (node instanceof AST_SymbolDefClass) { + // This deals with the name of the class being available + // inside the class. + mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1); + } else if (node instanceof AST_SymbolVar + || node instanceof AST_SymbolLet + || node instanceof AST_SymbolConst) { + var def; + if (node instanceof AST_SymbolBlockDeclaration) { + def = scope.def_variable(node, null); + } else { + def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined); + } + if (!all(def.orig, function(sym) { + if (sym === node) return true; + if (node instanceof AST_SymbolBlockDeclaration) { + return sym instanceof AST_SymbolLambda; + } + return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst); + })) { + js_error( + node.name + " redeclared", + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2); + def.destructuring = in_destructuring; + if (defun !== scope) { + node.mark_enclosed(options); + var def = scope.find_variable(node); + if (node.thedef !== def) { + node.thedef = def; + node.reference(options); + } + } + } else if (node instanceof AST_SymbolCatch) { + scope.def_variable(node).defun = defun; + } else if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) { + js_error( + node.TYPE + " statement may only appear at top level", + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + + function mark_export(def, level) { + if (in_destructuring) { + var i = 0; + do { + level++; + } while (tw.parent(i++) !== in_destructuring); + } + var node = tw.parent(level); + if (def.export = node instanceof AST_Export && MASK_EXPORT_DONT_MANGLE) { + var exported = node.exported_definition; + if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) { + def.export = MASK_EXPORT_WANT_MANGLE; + } + } + } + }); + self.walk(tw); + + // pass 2: find back references and eval + self.globals = new Dictionary(); + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_LoopControl && node.label) { + node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) { + s.uses_eval = true; + } + } + var sym; + if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name + || !(sym = node.scope.find_variable(name))) { + sym = self.def_global(node); + if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE; + } else if (sym.scope instanceof AST_Lambda && name == "arguments") { + sym.scope.uses_arguments = true; + } + node.thedef = sym; + node.reference(options); + if (node.scope.is_block_scope() + && !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) { + node.scope = node.scope.get_defun_scope(); + } + return true; + } + // ensure mangling works if catch reuses a scope variable + var def; + if (node instanceof AST_SymbolCatch && (def = node.definition().redefined())) { + var s = node.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } + } + }); + self.walk(tw); + + // pass 3: work around IE8 and Safari catch scope bugs + if (options.ie8 || options.safari10) { + self.walk(new TreeWalker(function(node, descend) { + if (node instanceof AST_SymbolCatch) { + var name = node.name; + var refs = node.thedef.references; + var scope = node.thedef.defun; + var def = scope.find_variable(name) || self.globals.get(name) || scope.def_variable(node); + refs.forEach(function(ref) { + ref.thedef = def; + ref.reference(options); + }); + node.thedef = def; + node.reference(options); + return true; + } + })); + } + + // pass 4: add symbol definitions to loop scopes + // Safari/Webkit bug workaround - loop init let variable shadowing argument. + // https://github.com/mishoo/UglifyJS2/issues/1753 + // https://bugs.webkit.org/show_bug.cgi?id=171041 + if (options.safari10) { + for (var i = 0; i < for_scopes.length; i++) { + var scope = for_scopes[i]; + scope.parent_scope.variables.each(function(def) { + push_uniq(scope.enclosed, def); + }); + } + } +}); + +AST_Toplevel.DEFMETHOD("def_global", function(node) { + var globals = this.globals, name = node.name; + if (globals.has(name)) { + return globals.get(name); + } else { + var g = new SymbolDef(this, node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + return g; + } +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) { + this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = parent_scope; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables +}); + +AST_Node.DEFMETHOD("is_block_scope", return_false); +AST_Class.DEFMETHOD("is_block_scope", return_false); +AST_Lambda.DEFMETHOD("is_block_scope", return_false); +AST_Toplevel.DEFMETHOD("is_block_scope", return_false); +AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false); +AST_Block.DEFMETHOD("is_block_scope", return_true); +AST_IterationStatement.DEFMETHOD("is_block_scope", return_true); + +AST_Lambda.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; + this.def_variable(new AST_SymbolFunarg({ + name: "arguments", + start: this.start, + end: this.end + })); +}); + +AST_Arrow.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; +}); + +AST_Symbol.DEFMETHOD("mark_enclosed", function(options) { + var def = this.definition(); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (options.keep_fnames) { + s.functions.each(function(d) { + if (keep_name(options.keep_fnames, d.name)) { + push_uniq(def.scope.enclosed, d); + } + }); + } + if (s === def.scope) break; + s = s.parent_scope; + } +}); + +AST_Symbol.DEFMETHOD("reference", function(options) { + this.definition().references.push(this); + this.mark_enclosed(options); +}); + +AST_Scope.DEFMETHOD("find_variable", function(name) { + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol, init) { + var def = this.def_variable(symbol, init); + if (!def.init || def.init instanceof AST_Defun) def.init = init; + this.functions.set(symbol.name, def); + return def; +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol, init) { + var def = this.variables.get(symbol.name); + if (def) { + def.orig.push(symbol); + if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) { + def.init = init; + } + } else { + def = new SymbolDef(this, symbol, init); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } + return symbol.thedef = def; +}); + +function next_mangled(scope, options) { + var ext = scope.enclosed; + out: while (true) { + var m = base54(++scope.cname); + if (!is_identifier(m)) continue; // skip over "do" + + // https://github.com/mishoo/UglifyJS2/issues/242 -- do not + // shadow a name reserved from mangling. + if (member(m, options.reserved)) continue; + + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (var i = ext.length; --i >= 0;) { + var sym = ext[i]; + var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); + if (m == name) continue out; + } + return m; + } +} + +AST_Scope.DEFMETHOD("next_mangled", function(options) { + return next_mangled(this, options); +}); + +AST_Toplevel.DEFMETHOD("next_mangled", function(options) { + var name; + do { + name = next_mangled(this, options); + } while (member(name, this.mangled_names)); + return name; +}); + +AST_Function.DEFMETHOD("next_mangled", function(options, def) { + // #179, #326 + // in Safari strict mode, something like (function x(x){...}) is a syntax error; + // a function expression's argument cannot shadow the function expression's name + + var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); + + // the function's mangled_name is null when keep_fnames is true + var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null; + + while (true) { + var name = next_mangled(this, options); + if (!tricky_name || tricky_name != name) + return name; + } +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options) { + var def = this.definition(); + return !def || def.unmangleable(options); +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", return_false); + +AST_Symbol.DEFMETHOD("unreferenced", function() { + return !this.definition().references.length && !this.scope.pinned(); +}); + +AST_Symbol.DEFMETHOD("definition", function() { + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function() { + return this.definition().global; +}); + +AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) { + options = defaults(options, { + eval : false, + ie8 : false, + keep_classnames: false, + keep_fnames : false, + module : false, + reserved : [], + toplevel : false, + }); + if (options["module"]) { + options.toplevel = true; + } + if (!Array.isArray(options.reserved)) options.reserved = []; + // Never mangle arguments + push_uniq(options.reserved, "arguments"); + return options; +}); + +AST_Toplevel.DEFMETHOD("mangle_names", function(options) { + options = this._default_mangler_options(options); + + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + + var mangled_names = this.mangled_names = []; + if (options.cache) { + this.globals.each(collect); + if (options.cache.props) { + options.cache.props.each(function(mangled_name) { + push_uniq(mangled_names, mangled_name); + }); + } + } + + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_Scope) { + node.variables.each(collect); + return; + } + if (node.is_block_scope()) { + node.block_scope.variables.each(collect); + return; + } + if (node instanceof AST_Label) { + var name; + do name = base54(++lname); while (!is_identifier(name)); + node.mangled_name = name; + return true; + } + if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) { + to_mangle.push(node.definition()); + return; + } + }); + this.walk(tw); + to_mangle.forEach(function(def) { def.mangle(options); }); + + function collect(symbol) { + if (!member(symbol.name, options.reserved)) { + if (!(symbol.export & MASK_EXPORT_DONT_MANGLE)) { + to_mangle.push(symbol); + } + } + } +}); + +AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) { + var cache = options.cache && options.cache.props; + var avoid = Object.create(null); + options.reserved.forEach(to_avoid); + this.globals.each(add_def); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.each(add_def); + if (node instanceof AST_SymbolCatch) add_def(node.definition()); + })); + return avoid; + + function to_avoid(name) { + avoid[name] = true; + } + + function add_def(def) { + var name = def.name; + if (def.global && cache && cache.has(name)) name = cache.get(name); + else if (!def.unmangleable(options)) return; + to_avoid(name); + } +}); + +AST_Toplevel.DEFMETHOD("expand_names", function(options) { + base54.reset(); + base54.sort(); + options = this._default_mangler_options(options); + var avoid = this.find_colliding_names(options); + var cname = 0; + this.globals.each(rename); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.each(rename); + if (node instanceof AST_SymbolCatch) rename(node.definition()); + })); + + function next_name() { + var name; + do { + name = base54(cname++); + } while (avoid[name] || !is_identifier(name)); + return name; + } + + function rename(def) { + if (def.global && options.cache) return; + if (def.unmangleable(options)) return; + if (member(def.name, options.reserved)) return; + var d = def.redefined(); + def.name = d ? d.name : next_name(); + def.orig.forEach(function(sym) { + sym.name = def.name; + }); + def.references.forEach(function(sym) { + sym.name = def.name; + }); + } +}); + +AST_Node.DEFMETHOD("tail_node", return_this); +AST_Sequence.DEFMETHOD("tail_node", function() { + return this.expressions[this.expressions.length - 1]; +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) { + options = this._default_mangler_options(options); + try { + AST_Node.prototype.print = function(stream, force_parens) { + this._print(stream, force_parens); + if (this instanceof AST_Symbol && !this.unmangleable(options)) { + base54.consider(this.name, -1); + } else if (options.properties) { + if (this instanceof AST_Dot) { + base54.consider(this.property, -1); + } else if (this instanceof AST_Sub) { + skip_string(this.property); + } + } + }; + base54.consider(this.print_to_string(), 1); + } finally { + AST_Node.prototype.print = AST_Node.prototype._print; + } + base54.sort(); + + function skip_string(node) { + if (node instanceof AST_String) { + base54.consider(node.value, -1); + } else if (node instanceof AST_Conditional) { + skip_string(node.consequent); + skip_string(node.alternative); + } else if (node instanceof AST_Sequence) { + skip_string(node.tail_node()); + } + } +}); + +var base54 = (function() { + var leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split(""); + var digits = "0123456789".split(""); + var chars, frequency; + function reset() { + frequency = Object.create(null); + leading.forEach(function(ch) { + frequency[ch] = 0; + }); + digits.forEach(function(ch) { + frequency[ch] = 0; + }); + } + base54.consider = function(str, delta) { + for (var i = str.length; --i >= 0;) { + frequency[str[i]] += delta; + } + }; + function compare(a, b) { + return frequency[b] - frequency[a]; + } + base54.sort = function() { + chars = mergeSort(leading, compare).concat(mergeSort(digits, compare)); + }; + base54.reset = reset; + reset(); + function base54(num) { + var ret = "", base = 54; + num++; + do { + num--; + ret += chars[num % base]; + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + } + return base54; +})(); +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +var EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/; + +function is_some_comments(comment) { + // multiline comment + return comment.type == "comment2" && /@preserve|@license|@cc_on/i.test(comment.value); +} + +function OutputStream(options) { + + var readonly = !options; + options = defaults(options, { + ascii_only : false, + beautify : false, + braces : false, + comments : false, + ecma : 5, + ie8 : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_quoted_props: false, + max_line_len : false, + preamble : null, + quote_keys : false, + quote_style : 0, + safari10 : false, + semicolons : true, + shebang : true, + shorthand : undefined, + source_map : null, + webkit : false, + width : 80, + wrap_iife : false, + }, true); + + if (options.shorthand === undefined) + options.shorthand = options.ecma > 5; + + // Convert comment option to RegExp if neccessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + var comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = ""; + + var to_utf8 = options.ascii_only ? function(str, identifier) { + if (options.ecma >= 6) { + str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) { + var code = get_full_char_code(ch, 0).toString(16); + return "\\u{" + code + "}"; + }); + } + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + } : function(str) { + var s = ""; + for (var i = 0, len = str.length; i < len; i++) { + if (is_surrogate_pair_head(str[i]) && !is_surrogate_pair_tail(str[i + 1]) + || is_surrogate_pair_tail(str[i]) && !is_surrogate_pair_head(str[i - 1])) { + s += "\\u" + str.charCodeAt(i).toString(16); + } else { + s += str[i]; + } + } + return s; + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, + function(s, i) { + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.ie8 ? "\\x0B" : "\\v"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-9]/.test(get_full_char(str, i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + function quote_template() { + return "`" + str.replace(/`/g, "\\`") + "`"; + } + str = to_utf8(str); + if (quote === "`") return quote_template(); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + } + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + } + + function make_name(name) { + name = name.toString(); + name = to_utf8(name, true); + return name; + } + + function make_indent(back) { + return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); + } + + /* -----[ beautification/minification ]----- */ + + var has_parens = false; + var might_need_space = false; + var might_need_semicolon = false; + var might_add_newline = 0; + var need_newline_indented = false; + var need_space = false; + var newline_insert = -1; + var last = ""; + var mapping_token, mapping_name, mappings = options.source_map && []; + + var do_add_mapping = mappings ? function() { + mappings.forEach(function(mapping) { + try { + options.source_map.add( + mapping.token.file, + mapping.line, mapping.col, + mapping.token.line, mapping.token.col, + !mapping.name && mapping.token.type == "name" ? mapping.token.value : mapping.name + ); + } catch(ex) { + mapping.token.file != null && AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { + file: mapping.token.file, + line: mapping.token.line, + col: mapping.token.col, + cline: mapping.line, + ccol: mapping.col, + name: mapping.name || "" + }); + } + }); + mappings = []; + } : noop; + + var ensure_line_len = options.max_line_len ? function() { + if (current_col > options.max_line_len) { + if (might_add_newline) { + var left = OUTPUT.slice(0, might_add_newline); + var right = OUTPUT.slice(might_add_newline); + if (mappings) { + var delta = right.length - current_col; + mappings.forEach(function(mapping) { + mapping.line++; + mapping.col += delta; + }); + } + OUTPUT = left + "\n" + right; + current_line++; + current_pos++; + current_col = right.length; + } + if (current_col > options.max_line_len) { + AST_Node.warn("Output exceeds {max_line_len} characters", options); + } + } + if (might_add_newline) { + might_add_newline = 0; + do_add_mapping(); + } + } : noop; + + var requireSemicolonChars = makePredicate("( [ + * / - , . `"); + + function print(str) { + str = String(str); + var ch = get_full_char(str, 0); + var prev = get_full_char(last, last.length - 1); + if (need_newline_indented && ch) { + need_newline_indented = false; + if (ch != "\n") { + print("\n"); + indent(); + } + } + if (need_space && ch) { + need_space = false; + if (!/[\s;})]/.test(ch)) { + space(); + } + } + newline_insert = -1; + var prev = last.charAt(last.length - 1); + if (might_need_semicolon) { + might_need_semicolon = false; + + if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") { + if (options.semicolons || requireSemicolonChars(ch)) { + OUTPUT += ";"; + current_col++; + current_pos++; + } else { + ensure_line_len(); + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (might_need_space) { + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last) + ) { + OUTPUT += " "; + current_col++; + current_pos++; + } + might_need_space = false; + } + + if (mapping_token) { + mappings.push({ + token: mapping_token, + name: mapping_name, + line: current_line, + col: current_col + }); + mapping_token = false; + if (!might_add_newline) do_add_mapping(); + } + + OUTPUT += str; + has_parens = str[str.length - 1] == "("; + current_pos += str.length; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + ensure_line_len(); + current_col = a[n].length; + } + last = str; + } + + var star = function() { + print("*"); + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont(); }; + + var newline = options.beautify ? function() { + if (newline_insert < 0) return print("\n"); + if (OUTPUT[newline_insert] != "\n") { + OUTPUT = OUTPUT.slice(0, newline_insert) + "\n" + OUTPUT.slice(newline_insert); + current_pos++; + current_line++; + } + newline_insert++; + } : options.max_line_len ? function() { + ensure_line_len(); + might_add_newline = OUTPUT.length; + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + } + + function next_indent() { + return indentation + options.indent_level; + } + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function() { + ret = cont(); + }); + indent(); + print("}"); + return ret; + } + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + } + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + } + + function comma() { + print(","); + space(); + } + + function colon() { + print(":"); + space(); + } + + var add_mapping = mappings ? function(token, name) { + mapping_token = token; + mapping_name = name; + } : noop; + + function get() { + if (might_add_newline) { + ensure_line_len(); + } + return OUTPUT; + } + + function has_nlb() { + var index = OUTPUT.lastIndexOf("\n"); + return /^ *$/.test(OUTPUT.slice(index + 1)); + } + + function prepend_comments(node) { + var self = this; + var start = node.start; + if (!start) return; + if (start.comments_before && start.comments_before._dumped === self) return; + var comments = start.comments_before; + if (!comments) { + comments = start.comments_before = []; + } + comments._dumped = self; + + if (node instanceof AST_Exit && node.value) { + var tw = new TreeWalker(function(node) { + var parent = tw.parent(); + if (parent instanceof AST_Exit + || parent instanceof AST_Binary && parent.left === node + || parent.TYPE == "Call" && parent.expression === node + || parent instanceof AST_Conditional && parent.condition === node + || parent instanceof AST_Dot && parent.expression === node + || parent instanceof AST_Sequence && parent.expressions[0] === node + || parent instanceof AST_Sub && parent.expression === node + || parent instanceof AST_UnaryPostfix) { + if (!node.start) return; + var text = node.start.comments_before; + if (text && text._dumped !== self) { + text._dumped = self; + comments = comments.concat(text); + } + } else { + return true; + } + }); + tw.push(node); + node.value.walk(tw); + } + + if (current_pos == 0) { + if (comments.length > 0 && options.shebang && comments[0].type == "comment5") { + print("#!" + comments.shift().value + "\n"); + indent(); + } + var preamble = options.preamble; + if (preamble) { + print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + } + + comments = comments.filter(comment_filter, node); + if (comments.length == 0) return; + var last_nlb = has_nlb(); + comments.forEach(function(c, i) { + if (!last_nlb) { + if (c.nlb) { + print("\n"); + indent(); + last_nlb = true; + } else if (i > 0) { + space(); + } + } + if (/comment[134]/.test(c.type)) { + print("//" + c.value.replace(/[@#]__PURE__/g, " ") + "\n"); + indent(); + last_nlb = true; + } else if (c.type == "comment2") { + print("/*" + c.value.replace(/[@#]__PURE__/g, " ") + "*/"); + last_nlb = false; + } + }); + if (!last_nlb) { + if (start.nlb) { + print("\n"); + indent(); + } else { + space(); + } + } + } + + function append_comments(node, tail) { + var self = this; + var token = node.end; + if (!token) return; + var comments = token[tail ? "comments_before" : "comments_after"]; + if (!comments || comments._dumped === self) return; + if (!(node instanceof AST_Statement || all(comments, function(c) { + return !/comment[134]/.test(c.type); + }))) return; + comments._dumped = self; + var insert = OUTPUT.length; + comments.filter(comment_filter, node).forEach(function(c, i) { + need_space = false; + if (need_newline_indented) { + print("\n"); + indent(); + need_newline_indented = false; + } else if (c.nlb && (i > 0 || !has_nlb())) { + print("\n"); + indent(); + } else if (i > 0 || !tail) { + space(); + } + if (/comment[134]/.test(c.type)) { + print("//" + c.value.replace(/[@#]__PURE__/g, " ")); + need_newline_indented = true; + } else if (c.type == "comment2") { + print("/*" + c.value.replace(/[@#]__PURE__/g, " ") + "*/"); + need_space = true; + } + }); + if (OUTPUT.length > insert) newline_insert = insert; + } + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + indentation : function() { return indentation; }, + current_width : function() { return current_col - indentation; }, + should_break : function() { return options.width && this.current_width() >= options.width; }, + has_parens : function() { return has_parens; }, + newline : newline, + print : print, + star : star, + space : space, + comma : comma, + colon : colon, + last : function() { return last; }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_utf8 : to_utf8, + print_name : function(name) { print(make_name(name)); }, + print_string : function(str, quote, escape_directive) { + var encoded = encode_string(str, quote); + if (escape_directive === true && encoded.indexOf("\\") === -1) { + // Insert semicolons to break directive prologue + if (!EXPECT_DIRECTIVE.test(OUTPUT)) { + force_semicolon(); + } + force_semicolon(); + } + print(encoded); + }, + print_template_string_chars: function(str) { + var encoded = encode_string(str, "`").replace(/\${/g, "\\${"); + return print(encoded.substr(1, encoded.length - 2)); + }, + encode_string : encode_string, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt]; }, + prepend_comments: readonly ? noop : prepend_comments, + append_comments : readonly || comment_filter === return_false ? noop : append_comments, + line : function() { return current_line; }, + col : function() { return current_col; }, + pos : function() { return current_pos; }, + push_node : function(node) { stack.push(node); }, + pop_node : function() { return stack.pop(); }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +} + +/* -----[ code generators ]----- */ + +(function() { + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + } + + var in_directive = false; + var active_scope = null; + var use_asm = null; + + AST_Node.DEFMETHOD("print", function(stream, force_parens) { + var self = this, generator = self._codegen; + if (self instanceof AST_Scope) { + active_scope = self; + } else if (!use_asm && self instanceof AST_Directive && self.value == "use asm") { + use_asm = active_scope; + } + function doit() { + stream.prepend_comments(self); + self.add_source_map(stream); + generator(self, stream); + stream.append_comments(self); + } + stream.push_node(self); + if (force_parens || self.needs_parens(stream)) { + stream.with_parens(doit); + } else { + doit(); + } + stream.pop_node(); + if (self === use_asm) { + use_asm = null; + } + }); + AST_Node.DEFMETHOD("_print", AST_Node.prototype.print); + + AST_Node.DEFMETHOD("print_to_string", function(options) { + var s = OutputStream(options); + this.print(s); + return s.get(); + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype) { + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + } + + PARENS(AST_Node, return_false); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output) { + if (!output.has_parens() && first_in_statement(output)) { + return true; + } + + if (output.option("webkit")) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + return true; + } + } + + if (output.option("wrap_iife")) { + var p = output.parent(); + return p instanceof AST_Call && p.expression === this; + } + + return false; + }); + + PARENS(AST_Arrow, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this; + }); + + // same goes for an object literal, because otherwise it would be + // interpreted as a block of code. + PARENS(AST_Object, function(output) { + return !output.has_parens() && first_in_statement(output); + }); + + PARENS(AST_ClassExpression, first_in_statement); + + PARENS(AST_Unary, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary + && p.operator === "**" + && this instanceof AST_UnaryPrefix + && p.left === this + && this.operator !== "++" + && this.operator !== "--"; + }); + + PARENS(AST_Await, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || output.option("safari10") && p instanceof AST_UnaryPrefix; + }); + + PARENS(AST_Sequence, function(output) { + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + || p instanceof AST_Arrow // x => (x, x) + || p instanceof AST_DefaultAssign // x => (x = (0, function(){})) + || p instanceof AST_Expansion // [...(a, b)] + || p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {} + || p instanceof AST_Yield // yield (foo, bar) + || p instanceof AST_Export // export default (foo, bar) + ; + }); + + PARENS(AST_Binary, function(output) { + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + var po = p.operator, pp = PRECEDENCE[po]; + var so = this.operator, sp = PRECEDENCE[so]; + if (pp > sp + || (pp == sp + && (this === p.right || po == "**"))) { + return true; + } + } + }); + + PARENS(AST_Yield, function(output) { + var p = output.parent(); + // (yield 1) + (yield 2) + // a = yield 3 + if (p instanceof AST_Binary && p.operator !== "=") + return true; + // (yield 1)() + // new (yield 1)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (yield 1) ? yield 2 : yield 3 + if (p instanceof AST_Conditional && p.condition === this) + return true; + // -(yield 4) + if (p instanceof AST_Unary) + return true; + // (yield x).foo + // (yield x)['foo'] + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + PARENS(AST_PropAccess, function(output) { + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + var parens = false; + this.walk(new TreeWalker(function(node) { + if (parens || node instanceof AST_Scope) return true; + if (node instanceof AST_Call) { + parens = true; + return true; + } + })); + return parens; + } + }); + + PARENS(AST_Call, function(output) { + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this + || p instanceof AST_Export && p.is_default && this.expression instanceof AST_Function) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output) { + var p = output.parent(); + if (!need_constructor_parens(this, output) + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value < 0 || /^0/.test(make_num(value))) { + return true; + } + } + }); + + PARENS([ AST_Assign, AST_Conditional ], function(output) { + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // ({a, b} = {a: 1, b: 2}), a destructuring assignment + if (this instanceof AST_Assign && this.left instanceof AST_Destructuring && this.left.is_array === false) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output) { + output.print_string(self.value, self.quote); + output.semicolon(); + }); + + DEFPRINT(AST_Expansion, function (self, output) { + output.print("..."); + self.expression.print(output); + }); + + DEFPRINT(AST_Destructuring, function (self, output) { + output.print(self.is_array ? "[" : "{"); + var len = self.names.length; + self.names.forEach(function (name, i) { + if (i > 0) output.comma(); + name.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i == len - 1 && name instanceof AST_Hole) output.comma(); + }); + output.print(self.is_array ? "]" : "}"); + }); + + DEFPRINT(AST_Debugger, function(self, output) { + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + in_directive = allow_directives; + body.forEach(function(stmt, i) { + if (in_directive === true && !(stmt instanceof AST_Directive || + stmt instanceof AST_EmptyStatement || + (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) + )) { + in_directive = false; + } + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + if (in_directive === true && + stmt instanceof AST_SimpleStatement && + stmt.body instanceof AST_String + ) { + in_directive = false; + } + }); + in_directive = false; + } + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) { + force_statement(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output) { + display_body(self.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output) { + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + function print_braced_empty(self, output) { + output.print("{"); + output.with_indent(output.next_indent(), function() { + output.append_comments(self, true); + }); + output.print("}"); + } + function print_braced(self, output, allow_directives) { + if (self.body.length > 0) { + output.with_block(function() { + display_body(self.body, false, output, allow_directives); + }); + } else print_braced_empty(self, output); + } + DEFPRINT(AST_BlockStatement, function(self, output) { + print_braced(self, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output) { + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output) { + output.print("do"); + output.space(); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output) { + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output) { + output.print("for"); + output.space(); + output.with_parens(function() { + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output) { + output.print("for"); + if (self.await) { + output.space(); + output.print("await"); + } + output.space(); + output.with_parens(function() { + self.init.print(output); + output.space(); + output.print(self instanceof AST_ForOf ? "of" : "in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output) { + output.print("with"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) { + var self = this; + if (!nokeyword) { + if (self.async) { + output.print("async"); + output.space(); + } + output.print("function"); + if (self.is_generator) { + output.star(); + } + if (self.name) { + output.space(); + } + } + if (self.name instanceof AST_Symbol) { + self.name.print(output); + } else if (nokeyword && self.name instanceof AST_Node) { + output.with_square(function() { + self.name.print(output); // Computed method name + }); + } + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_braced(self, output, true); + }); + DEFPRINT(AST_Lambda, function(self, output) { + self._do_print(output); + }); + + DEFPRINT(AST_PrefixedTemplateString, function(self, output) { + var tag = self.prefix; + var parenthesize_tag = tag instanceof AST_Arrow + || tag instanceof AST_Binary + || tag instanceof AST_Conditional + || tag instanceof AST_Sequence + || tag instanceof AST_Unary; + if (parenthesize_tag) output.print("("); + self.prefix.print(output); + if (parenthesize_tag) output.print(")"); + self.template_string.print(output); + }); + DEFPRINT(AST_TemplateString, function(self, output) { + var is_tagged = output.parent() instanceof AST_PrefixedTemplateString; + + output.print("`"); + for (var i = 0; i < self.segments.length; i++) { + if (!(self.segments[i] instanceof AST_TemplateSegment)) { + output.print("${"); + self.segments[i].print(output); + output.print("}"); + } else if (is_tagged) { + output.print(self.segments[i].raw); + } else { + output.print_template_string_chars(self.segments[i].value); + } + } + output.print("`"); + }); + + AST_Arrow.DEFMETHOD("_do_print", function(output) { + var self = this; + var parent = output.parent(); + var needs_parens = parent instanceof AST_Binary || + parent instanceof AST_Unary || + (parent instanceof AST_Call && self === parent.expression); + if (needs_parens) { output.print("("); } + if (self.async) { + output.print("async"); + output.space(); + } + if (self.argnames.length === 1 && self.argnames[0] instanceof AST_Symbol) { + self.argnames[0].print(output); + } else { + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + } + output.space(); + output.print("=>"); + output.space(); + if (self.body instanceof AST_Node) { + self.body.print(output); + } else { + print_braced(self, output); + } + if (needs_parens) { output.print(")"); } + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.value) { + output.space(); + this.value.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output) { + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output) { + self._do_print(output, "throw"); + }); + + /* -----[ yield ]----- */ + + DEFPRINT(AST_Yield, function(self, output) { + var star = self.is_star ? "*" : ""; + output.print("yield" + star); + if (self.expression) { + output.space(); + self.expression.print(output); + } + }); + + DEFPRINT(AST_Await, function(self, output) { + output.print("await"); + output.space(); + var e = self.expression; + var parens = !( + e instanceof AST_Call + || e instanceof AST_SymbolRef + || e instanceof AST_PropAccess + || e instanceof AST_Unary + || e instanceof AST_Constant + ); + if (parens) output.print("("); + self.expression.print(output); + if (parens) output.print(")"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output) { + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output) { + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("braces") + || output.option("ie8") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block braces if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } else if (b instanceof AST_StatementWithBody) { + b = b.body; + } else break; + } + force_statement(self.body, output); + } + DEFPRINT(AST_If, function(self, output) { + output.print("if"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + if (self.alternative instanceof AST_If) + self.alternative.print(output); + else + force_statement(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output) { + output.print("switch"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) print_braced_empty(self, output); + else output.with_block(function() { + self.body.forEach(function(branch, i) { + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) { + output.newline(); + this.body.forEach(function(stmt) { + output.indent(); + stmt.print(output); + output.newline(); + }); + }); + DEFPRINT(AST_Default, function(self, output) { + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output) { + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output) { + output.print("try"); + output.space(); + print_braced(self, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(self, output) { + output.print("catch"); + if (self.argname) { + output.space(); + output.with_parens(function() { + self.argname.print(output); + }); + } + output.space(); + print_braced(self, output); + }); + DEFPRINT(AST_Finally, function(self, output) { + output.print("finally"); + output.space(); + print_braced(self, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i) { + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var output_semicolon = !in_for || p && p.init !== this; + if (output_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Let, function(self, output) { + self._do_print(output, "let"); + }); + DEFPRINT(AST_Var, function(self, output) { + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output) { + self._do_print(output, "const"); + }); + DEFPRINT(AST_Import, function(self, output) { + output.print("import"); + output.space(); + if (self.imported_name) { + self.imported_name.print(output); + } + if (self.imported_name && self.imported_names) { + output.print(","); + output.space(); + } + if (self.imported_names) { + if (self.imported_names.length === 1 && self.imported_names[0].foreign_name.name === "*") { + self.imported_names[0].print(output); + } else { + output.print("{"); + self.imported_names.forEach(function (name_import, i) { + output.space(); + name_import.print(output); + if (i < self.imported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } + if (self.imported_name || self.imported_names) { + output.space(); + output.print("from"); + output.space(); + } + self.module_name.print(output); + output.semicolon(); + }); + + DEFPRINT(AST_NameMapping, function(self, output) { + var is_import = output.parent() instanceof AST_Import; + var definition = self.name.definition(); + var names_are_different = + (definition && definition.mangled_name || self.name.name) !== + self.foreign_name.name; + if (names_are_different) { + if (is_import) { + output.print(self.foreign_name.name); + } else { + self.name.print(output); + } + output.space(); + output.print("as"); + output.space(); + if (is_import) { + self.name.print(output); + } else { + output.print(self.foreign_name.name); + } + } else { + self.name.print(output); + } + }); + + DEFPRINT(AST_Export, function(self, output) { + output.print("export"); + output.space(); + if (self.is_default) { + output.print("default"); + output.space(); + } + if (self.exported_names) { + if (self.exported_names.length === 1 && self.exported_names[0].name.name === "*") { + self.exported_names[0].print(output); + } else { + output.print("{"); + self.exported_names.forEach(function(name_export, i) { + output.space(); + name_export.print(output); + if (i < self.exported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } else if (self.exported_value) { + self.exported_value.print(output); + } else if (self.exported_definition) { + self.exported_definition.print(output); + if (self.exported_definition instanceof AST_Definitions) return; + } + if (self.module_name) { + output.space(); + output.print("from"); + output.space(); + self.module_name.print(output); + } + if (self.exported_value + && !(self.exported_value instanceof AST_Defun || + self.exported_value instanceof AST_Function || + self.exported_value instanceof AST_Class) + || self.module_name + || self.exported_names + ) { + output.semicolon(); + } + }); + + function parenthesize_for_noin(node, output, noin) { + var parens = false; + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + if (noin) node.walk(new TreeWalker(function(node) { + if (parens || node instanceof AST_Scope) return true; + if (node instanceof AST_Binary && node.operator == "in") { + parens = true; + return true; + } + })); + node.print(output, parens); + } + + DEFPRINT(AST_VarDef, function(self, output) { + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output) { + self.expression.print(output); + if (self instanceof AST_New && !need_constructor_parens(self, output)) + return; + if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) { + output.add_mapping(self.start); + } + output.with_parens(function() { + self.args.forEach(function(expr, i) { + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output) { + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Sequence.DEFMETHOD("_do_print", function(output) { + this.expressions.forEach(function(node, index) { + if (index > 0) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + } + node.print(output); + }); + }); + DEFPRINT(AST_Sequence, function(self, output) { + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + if (output.option("ie8") && RESERVED_WORDS(prop)) { + output.print("["); + output.add_mapping(self.end); + output.print_string(prop); + output.print("]"); + } else { + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.)]/i.test(output.last())) { + output.print("."); + } + } + output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(prop); + } + }); + DEFPRINT(AST_Sub, function(self, output) { + self.expression.print(output); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output) { + var op = self.operator; + output.print(op); + if (/^[a-z]/i.test(op) + || (/[+-]$/.test(op) + && self.expression instanceof AST_UnaryPrefix + && /^[+-]/.test(self.expression.operator))) { + output.space(); + } + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(self, output) { + self.expression.print(output); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(self, output) { + var op = self.operator; + self.left.print(output); + if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ + && self.left instanceof AST_UnaryPostfix + && self.left.operator == "--") { + // space is mandatory to avoid outputting --> + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + if ((op == "<" || op == "<<") + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "!" + && self.right.expression instanceof AST_UnaryPrefix + && self.right.expression.operator == "--") { + // space is mandatory to avoid outputting