Skip to content

Commit

Permalink
Fix optional chain optimization in sequence expression (#15888)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Aug 25, 2023
1 parent 148faa0 commit 0534e63
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import {
} from "@babel/helper-skip-transparent-expression-wrappers";
import { willPathCastToBoolean, findOutermostTransparentParent } from "./util";

// TODO(Babel 9): Use .at(-1)
const last = <T>(arr: T[]) => arr[arr.length - 1];

function isSimpleMemberExpression(
expression: t.Expression | t.Super,
): expression is t.Identifier | t.Super | t.MemberExpression {
Expand Down Expand Up @@ -209,9 +212,10 @@ export function transformOptionalChain(
!ifNullishBoolean && t.isUnaryExpression(ifNullish, { operator: "void" });

const isEvaluationValueIgnored =
(t.isExpressionStatement(replacementPath.parent) ||
t.isSequenceExpression(replacementPath.parent)) &&
!replacementPath.isCompletionRecord();
(t.isExpressionStatement(replacementPath.parent) &&
!replacementPath.isCompletionRecord()) ||
(t.isSequenceExpression(replacementPath.parent) &&
last(replacementPath.parent.expressions) !== replacementPath.node);

// prettier-ignore
const tpl = ifNullishFalse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ var _foo, _a, _a$b, _a$b$c, _orders, _orders2, _client, _orders$client$key, _a2,
(_orders2 = orders) === null || _orders2 === void 0 || (_orders2 = _orders2[0]) === null || _orders2 === void 0 || _orders2.price;
orders[(_client = client) === null || _client === void 0 ? void 0 : _client.key].price;
(_orders$client$key = orders[client.key]) === null || _orders$client$key === void 0 || _orders$client$key.price;
(0, (_a2 = a) === null || _a2 === void 0 || _a2.b).c;
(0, (_a2 = a) === null || _a2 === void 0 ? void 0 : _a2.b).c;
(0, (_c = (0, (_a3 = a) === null || _a3 === void 0 ? void 0 : _a3.b).c) === null || _c === void 0 ? void 0 : _c.d).e;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
let a = (0, null?.prop);

expect(a).toBe(undefined);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
let a = (null?.prop1, null?.prop2);

expect(a).toBe(undefined);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
var _ref, _ref2;
let a = ((_ref = null) !== null && _ref !== void 0 && _ref.prop1, (_ref2 = null) === null || _ref2 === void 0 ? void 0 : _ref2.prop2);
expect(a).toBe(undefined);

0 comments on commit 0534e63

Please sign in to comment.