From 6bc10b5573df7244170bc84840bad5d2fb992a7a Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Tue, 18 Oct 2016 01:55:02 +0300 Subject: [PATCH] Support ObjectExpression in static path evaluation (#4746) --- packages/babel-core/test/evaluation.js | 5 +++- .../babel-traverse/src/path/evaluation.js | 29 ++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/babel-core/test/evaluation.js b/packages/babel-core/test/evaluation.js index be9cc2a66c..1af3bc7399 100644 --- a/packages/babel-core/test/evaluation.js +++ b/packages/babel-core/test/evaluation.js @@ -10,7 +10,7 @@ describe("evaluation", function () { visitor[type] = function (path) { let evaluate = path.evaluate(); assert.equal(evaluate.confident, !notConfident); - assert.equal(evaluate.value, value); + assert.deepEqual(evaluate.value, value); }; traverse(parse(code, { @@ -63,4 +63,7 @@ describe("evaluation", function () { addTest("'abc' === 'xyz' || (1 === 1 && config.flag)", "LogicalExpression", undefined, true); addTest("'abc' === 'xyz' || (1 === 1 && 'four' === 'four')", "LogicalExpression", true); addTest("'abc' === 'abc' && (1 === 1 && 'four' === 'four')", "LogicalExpression", true); + addTest("({})", "ObjectExpression", {}); + addTest("({a: '1'})", "ObjectExpression", {a: "1"}); + addTest("({['a' + 'b']: 10 * 20, 'z': [1, 2, 3]})", "ObjectExpression", {ab: 200, z: [1, 2, 3]}); }); diff --git a/packages/babel-traverse/src/path/evaluation.js b/packages/babel-traverse/src/path/evaluation.js index 6dcc3f747f..ef478103b1 100644 --- a/packages/babel-traverse/src/path/evaluation.js +++ b/packages/babel-traverse/src/path/evaluation.js @@ -231,7 +231,34 @@ export function evaluate(): { confident: boolean; value: any } { } if (path.isObjectExpression()) { - // todo + let obj = {}; + let props: Array = path.get("properties"); + for (let prop of props) { + if (prop.isObjectMethod() || prop.isSpreadProperty()) { + return deopt(prop); + } + const keyPath = prop.get("key"); + let key = keyPath; + if (prop.node.computed) { + key = key.evaluate(); + if (!key.confident) { + return deopt(keyPath); + } + key = key.value; + } else if (key.isIdentifier()) { + key = key.node.name; + } else { + key = key.node.value; + } + const valuePath = prop.get("value"); + let value = valuePath.evaluate(); + if (!value.confident) { + return deopt(valuePath); + } + value = value.value; + obj[key] = value; + } + return obj; } if (path.isLogicalExpression()) {