Huáng Jùnliàng 5f83a8c1a2
Handle cases when ?? and ?. is in binding initializers (#12032)
* test: add test for nullish coalescing

Co-Authored-By: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>

* test: add control group

* test: add tests for optional chaining

Co-Authored-By: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>

* test: add tests on optional chaining mixed with private class elements

* fix: wrap member chains to IIFE when it is in parameter default

* chore: add more testcases

* chore: update test fixtures

* fix: NodePath.get is always non nullish

Co-authored-by: Nicolò Ribaudo <nicolo.ribaudo@gmail.com>
2020-10-03 10:03:58 -04:00

60 lines
2.0 KiB
JavaScript

import { declare } from "@babel/helper-plugin-utils";
import syntaxNullishCoalescingOperator from "@babel/plugin-syntax-nullish-coalescing-operator";
import { types as t, template } from "@babel/core";
export default declare((api, { loose = false }) => {
api.assertVersion(7);
return {
name: "proposal-nullish-coalescing-operator",
inherits: syntaxNullishCoalescingOperator,
visitor: {
LogicalExpression(path) {
const { node, scope } = path;
if (node.operator !== "??") {
return;
}
let ref;
let assignment;
// skip creating extra reference when `left` is static
if (scope.isStatic(node.left)) {
ref = node.left;
assignment = t.cloneNode(node.left);
} else if (scope.path.isPattern()) {
// Replace `function (a, x = a.b ?? c) {}` to `function (a, x = (() => a.b ?? c)() ){}`
// so the temporary variable can be injected in correct scope
path.replaceWith(template.ast`(() => ${path.node})()`);
// The injected nullish expression will be queued and eventually transformed when visited
return;
} else {
ref = scope.generateUidIdentifierBasedOnNode(node.left);
scope.push({ id: t.cloneNode(ref) });
assignment = t.assignmentExpression("=", ref, node.left);
}
path.replaceWith(
t.conditionalExpression(
// We cannot use `!= null` in spec mode because
// `document.all == null` and `document.all` is not "nullish".
loose
? t.binaryExpression("!=", assignment, t.nullLiteral())
: t.logicalExpression(
"&&",
t.binaryExpression("!==", assignment, t.nullLiteral()),
t.binaryExpression(
"!==",
t.cloneNode(ref),
scope.buildUndefinedNode(),
),
),
t.cloneNode(ref),
node.right,
),
);
},
},
};
});