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

fix: Expression x === 'y' && '' should not evaluate to undefined. #8880

Merged
merged 1 commit into from Oct 16, 2018
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 3 additions & 11 deletions packages/babel-traverse/src/path/evaluation.js
Expand Up @@ -257,33 +257,25 @@ function _evaluate(path, state) {
}

if (path.isLogicalExpression()) {
// If we are confident that one side of an && is false, or the left
// If we are confident that the left side of an && is false, or the left
// side of an || is true, we can be confident about the entire expression
const wasConfident = state.confident;
const left = evaluateCached(path.get("left"), state);
const leftConfident = state.confident;
state.confident = wasConfident;
const right = evaluateCached(path.get("right"), state);
const rightConfident = state.confident;
state.confident = leftConfident && rightConfident;

switch (node.operator) {
case "||":
// TODO consider having a "truthy type" that doesn't bail on
// left uncertainty but can still evaluate to truthy.
if (left && leftConfident) {
state.confident = true;
return left;
}

state.confident = leftConfident && (!!left || rightConfident);
if (!state.confident) return;

return left || right;
case "&&":
if ((!left && leftConfident) || (!right && rightConfident)) {
state.confident = true;
}
state.confident = leftConfident && (!left || rightConfident);
if (!state.confident) return;
return left && right;
Expand Down
23 changes: 23 additions & 0 deletions packages/babel-traverse/test/evaluation.js
Expand Up @@ -40,6 +40,29 @@ describe("evaluation", function() {
).toBe(false);
});

it("should short-circuit && and ||", function() {
expect(
getPath("x === 'y' || 42")
.get("body")[0]
.evaluate().confident,
).toBe(false);
expect(
getPath("x === 'y' && 0")
.get("body")[0]
.evaluate().confident,
).toBe(false);
expect(
getPath("42 || x === 'y'")
.get("body")[0]
.evaluate().value,
).toBe(42);
expect(
getPath("0 && x === 'y'")
.get("body")[0]
.evaluate().value,
).toBe(0);
});

it("should work with repeated, indeterminate identifiers", function() {
expect(
getPath("var num = foo(); (num > 0 && num < 100);")
Expand Down