index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _pluginSyntaxNullishCoalescingOperator = require("@babel/plugin-syntax-nullish-coalescing-operator");
  8. var _core = require("@babel/core");
  9. var _default = (0, _helperPluginUtils.declare)((api, {
  10. loose = false
  11. }) => {
  12. var _api$assumption;
  13. api.assertVersion(7);
  14. const noDocumentAll = (_api$assumption = api.assumption("noDocumentAll")) != null ? _api$assumption : loose;
  15. return {
  16. name: "proposal-nullish-coalescing-operator",
  17. inherits: _pluginSyntaxNullishCoalescingOperator.default,
  18. visitor: {
  19. LogicalExpression(path) {
  20. const {
  21. node,
  22. scope
  23. } = path;
  24. if (node.operator !== "??") {
  25. return;
  26. }
  27. let ref;
  28. let assignment;
  29. if (scope.isStatic(node.left)) {
  30. ref = node.left;
  31. assignment = _core.types.cloneNode(node.left);
  32. } else if (scope.path.isPattern()) {
  33. path.replaceWith(_core.template.ast`(() => ${path.node})()`);
  34. return;
  35. } else {
  36. ref = scope.generateUidIdentifierBasedOnNode(node.left);
  37. scope.push({
  38. id: _core.types.cloneNode(ref)
  39. });
  40. assignment = _core.types.assignmentExpression("=", ref, node.left);
  41. }
  42. path.replaceWith(_core.types.conditionalExpression(noDocumentAll ? _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));
  43. }
  44. }
  45. };
  46. });
  47. exports.default = _default;