Implement transform for nullish-coalescing operator (#6483)

* Implement transform for nullish-coalescing operator

* Update example output

* Switch from BinaryExpression to LogicalExpression

* Address review comments

- Use generateUidIdentifierBasedOnNode
- Inline "??"
- Clone ref node
- Move "??" to LogicalExpression in babel-types

* Fix reference to @babel/helper-plugin-test-runner

* Fix reference to @babel/plugin-syntax-nullish-coalescing-operator

* Don't use parent scope

* Remove .vscode from .gitignore, change 'lib/index.js' to 'lib'

* Ensure `document.all ?? 0 === document.all`

* Fix note and copy to an inline comment
This commit is contained in:
Lucas Azzola
2017-10-18 18:10:05 +11:00
committed by Justin Ridgewell
parent 5c47929983
commit 99be60b53d
20 changed files with 219 additions and 1 deletions

View File

@@ -0,0 +1,40 @@
import syntaxNullishCoalescingOperator from "@babel/plugin-syntax-nullish-coalescing-operator";
export default function({ types: t }) {
return {
inherits: syntaxNullishCoalescingOperator,
visitor: {
LogicalExpression(path) {
const { node, scope } = path;
if (node.operator !== "??") {
return;
}
const ref = scope.generateUidIdentifierBasedOnNode(node.left);
scope.push({ id: ref });
path.replaceWith(
t.sequenceExpression([
t.assignmentExpression("=", ref, node.left),
t.conditionalExpression(
// We cannot use `!= null` here because `document.all == null`
// and `document.all` has been deemed not "nullish".
t.logicalExpression(
"&&",
t.binaryExpression("!==", t.clone(ref), t.nullLiteral()),
t.binaryExpression(
"!==",
t.clone(ref),
scope.buildUndefinedNode(),
),
),
t.clone(ref),
node.right,
),
]),
);
},
},
};
}