From 431a44bc74de4b038f8573e63725688998aef9fd Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Sun, 4 Jan 2015 12:15:24 +0200 Subject: [PATCH] Add support for destructuring defaults (not for shorthand props yet). Related to #181. --- acorn.js | 9 +++++ test/tests-harmony.js | 78 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/acorn.js b/acorn.js index 1d33a45194..aa9b60664e 100644 --- a/acorn.js +++ b/acorn.js @@ -1412,6 +1412,14 @@ } break; + case "AssignmentExpression": + if (node.operator === "=") { + node.type = "AssignmentPattern"; + } else { + unexpected(node.left.end); + } + break; + default: if (checkType) unexpected(node.start); } @@ -1508,6 +1516,7 @@ } break; + case "AssignmentPattern": case "SpreadElement": break; diff --git a/test/tests-harmony.js b/test/tests-harmony.js index c7cd8ea072..f59838c0d3 100644 --- a/test/tests-harmony.js +++ b/test/tests-harmony.js @@ -14373,3 +14373,81 @@ test('var {get} = obj;', { kind: "var" }] }, {ecmaVersion: 6}); + +// Destructuring defaults (https://github.com/marijnh/acorn/issues/181) + +test("var {propName: localVar = defaultValue} = obj", { + type: "Program", + body: [{ + type: "VariableDeclaration", + declarations: [{ + type: "VariableDeclarator", + id: { + type: "ObjectPattern", + properties: [{ + type: "Property", + method: false, + shorthand: false, + computed: false, + key: { + type: "Identifier", + name: "propName" + }, + value: { + type: "AssignmentPattern", + operator: "=", + left: { + type: "Identifier", + name: "localVar" + }, + right: { + type: "Identifier", + name: "defaultValue" + } + }, + kind: "init" + }] + }, + init: { + type: "Identifier", + name: "obj" + } + }], + kind: "var" + }] +}, {ecmaVersion: 6}); + +test("var [a = 1, b = 2] = arr", { + type: "Program", + body: [{ + type: "VariableDeclaration", + declarations: [{ + type: "VariableDeclarator", + id: { + type: "ArrayPattern", + elements: [ + { + type: "AssignmentPattern", + operator: "=", + left: {type: "Identifier", name: "a"}, + right: { + type: "Literal", + value: 1 + } + }, + { + type: "AssignmentPattern", + operator: "=", + left: {type: "Identifier", name: "b"}, + right: { + type: "Literal", + value: 2 + } + } + ] + }, + init: {type: "Identifier", name: "arr"} + }], + kind: "var" + }] +}, {ecmaVersion: 6});