trailing_comma_arguments.js (2389B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 // Trailing comma in Arguments production. 6 7 // 12.3 Left-Hand-Side Expressions 8 // Arguments[Yield]: 9 // () 10 // ( ArgumentList[?Yield] ) 11 // ( ArgumentList[?Yield] , ) 12 13 14 function argsLength() { 15 return {value: arguments.length}; 16 } 17 function sum(...rest) { 18 return {value: rest.reduce((a, c) => a + c, 0)}; 19 } 20 21 function call(f, argList) { 22 return eval(`(${f}(${argList})).value`); 23 } 24 25 function newCall(F, argList) { 26 return eval(`(new ${F}(${argList})).value`); 27 } 28 29 function superCall(superClass, argList) { 30 return eval(`(new class extends ${superClass} { 31 constructor() { 32 super(${argList}); 33 } 34 }).value`); 35 } 36 37 // Ensure the correct number of arguments is passed. 38 for (let type of [call, newCall, superCall]) { 39 let test = type.bind(null, "argsLength"); 40 41 assertEq(test("10, "), 1); 42 assertEq(test("10, 20, "), 2); 43 assertEq(test("10, 20, 30, "), 3); 44 assertEq(test("10, 20, 30, 40, "), 4); 45 46 assertEq(test("...[10, 20], "), 2); 47 assertEq(test("...[10, 20], 30, "), 3); 48 assertEq(test("...[10, 20], ...[30], "), 3); 49 } 50 51 // Ensure the arguments themselves are passed correctly. 52 for (let type of [call, newCall, superCall]) { 53 let test = type.bind(null, "sum"); 54 55 assertEq(test("10, "), 10); 56 assertEq(test("10, 20, "), 30); 57 assertEq(test("10, 20, 30, "), 60); 58 assertEq(test("10, 20, 30, 40, "), 100); 59 60 assertEq(test("...[10, 20], "), 30); 61 assertEq(test("...[10, 20], 30, "), 60); 62 assertEq(test("...[10, 20], ...[30], "), 60); 63 } 64 65 // Error cases. 66 for (let type of [call, newCall, superCall]) { 67 let test = type.bind(null, "f"); 68 69 // Trailing comma in empty arguments list. 70 assertThrowsInstanceOf(() => test(","), SyntaxError); 71 72 // Leading comma. 73 assertThrowsInstanceOf(() => test(", a"), SyntaxError); 74 assertThrowsInstanceOf(() => test(", ...a"), SyntaxError); 75 76 // Multiple trailing comma. 77 assertThrowsInstanceOf(() => test("a, , "), SyntaxError); 78 assertThrowsInstanceOf(() => test("...a, , "), SyntaxError); 79 80 // Elision. 81 assertThrowsInstanceOf(() => test("a, , b"), SyntaxError); 82 } 83 84 if (typeof reportCompare === "function") 85 reportCompare(0, 0);