Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support ObjectExpression in static path evaluation #4746

Merged
merged 1 commit into from
Oct 17, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/babel-core/test/evaluation.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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]});
});
29 changes: 28 additions & 1 deletion packages/babel-traverse/src/path/evaluation.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,34 @@ export function evaluate(): { confident: boolean; value: any } {
}

if (path.isObjectExpression()) {
// todo
let obj = {};
let props: Array<NodePath> = 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()) {
Expand Down