UNPKG

1.84 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _helperPluginUtils = require("@babel/helper-plugin-utils");
9
10var _pluginSyntaxNullishCoalescingOperator = _interopRequireDefault(require("@babel/plugin-syntax-nullish-coalescing-operator"));
11
12var _core = require("@babel/core");
13
14function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
16var _default = (0, _helperPluginUtils.declare)((api, {
17 loose = false
18}) => {
19 api.assertVersion(7);
20 return {
21 name: "proposal-nullish-coalescing-operator",
22 inherits: _pluginSyntaxNullishCoalescingOperator.default,
23 visitor: {
24 LogicalExpression(path) {
25 const {
26 node,
27 scope
28 } = path;
29
30 if (node.operator !== "??") {
31 return;
32 }
33
34 let ref;
35 let assignment;
36
37 if (scope.isStatic(node.left)) {
38 ref = node.left;
39 assignment = _core.types.cloneNode(node.left);
40 } else if (scope.path.isPattern()) {
41 path.replaceWith(_core.template.ast`(() => ${path.node})()`);
42 return;
43 } else {
44 ref = scope.generateUidIdentifierBasedOnNode(node.left);
45 scope.push({
46 id: _core.types.cloneNode(ref)
47 });
48 assignment = _core.types.assignmentExpression("=", ref, node.left);
49 }
50
51 path.replaceWith(_core.types.conditionalExpression(loose ? _core.types.binaryExpression("!=", assignment, _core.types.nullLiteral()) : _core.types.logicalExpression("&&", _core.types.binaryExpression("!==", assignment, _core.types.nullLiteral()), _core.types.binaryExpression("!==", _core.types.cloneNode(ref), scope.buildUndefinedNode())), _core.types.cloneNode(ref), node.right));
52 }
53
54 }
55 };
56});
57
58exports.default = _default;
\No newline at end of file