Example #1
1
  pushConstructor(
    replaceSupers,
    method: { type: "ClassMethod" },
    path: NodePath,
  ) {
    this.bareSupers = replaceSupers.bareSupers;
    this.superReturns = replaceSupers.returns;

    // https://github.com/babel/babel/issues/1077
    if (path.scope.hasOwnBinding(this.classRef.name)) {
      path.scope.rename(this.classRef.name);
    }

    const construct = this.constructor;

    this.userConstructorPath = path;
    this.userConstructor = method;
    this.hasConstructor = true;

    t.inheritsComments(construct, method);

    construct.params = method.params;

    t.inherits(construct.body, method.body);
    construct.body.directives = method.body.directives;

    // push constructor to body
    this._pushConstructor();
  }
Example #2
0
function getCodeForExpression(expressionNode) {
  return babel.transformFromAst(babel.types.program([
    babel.types.expressionStatement(
      babel.types.removeComments(babel.types.cloneDeep(expressionNode))
    )
  ])).code;
}
Example #3
0
  function extractNormalizedKeys(path) {
    var props = path.node.properties;
    var keys = [];
    var allLiteral = true;

    for (var _iterator2 = props, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
      var _ref2;

      if (_isArray2) {
        if (_i2 >= _iterator2.length) break;
        _ref2 = _iterator2[_i2++];
      } else {
        _i2 = _iterator2.next();
        if (_i2.done) break;
        _ref2 = _i2.value;
      }

      var _prop2 = _ref2;

      if (_core.types.isIdentifier(_prop2.key) && !_prop2.computed) {
        keys.push(_core.types.stringLiteral(_prop2.key.name));
      } else if (_core.types.isLiteral(_prop2.key)) {
        keys.push(_core.types.stringLiteral(String(_prop2.key.value)));
      } else {
        keys.push(_core.types.cloneNode(_prop2.key));
        allLiteral = false;
      }
    }

    return {
      keys: keys,
      allLiteral: allLiteral
    };
  }
Example #4
0
 .reduce(function(acc, decorator) {
   return buildClassDecorator({
     CLASS_REF: t.cloneNode(name),
     DECORATOR: t.cloneNode(decorator),
     INNER: acc,
   }).expression;
 }, classPath.node);
Example #5
0
export default function() {
  const yieldStarVisitor = {
    Function(path) {
      path.skip();
    },

    YieldExpression({ node }, state) {
      if (!node.delegate) return;
      const callee = state.addHelper("asyncGeneratorDelegate");
      node.argument = t.callExpression(callee, [
        t.callExpression(state.addHelper("asyncIterator"), [node.argument]),
        state.addHelper("awaitAsyncGenerator"),
      ]);
    },
  };

  return {
    inherits: syntaxAsyncGenerators,
    visitor: {
      Function(path, state) {
        if (!path.node.async || !path.node.generator) return;

        path.traverse(yieldStarVisitor, state);

        remapAsyncToGenerator(path, state.file, {
          wrapAsync: state.addHelper("wrapAsyncGenerator"),
          wrapAwait: state.addHelper("awaitAsyncGenerator"),
        });
      },
    },
  };
}
Example #6
0
    AssignmentExpression: function AssignmentExpression(path) {
      var _this = this;

      var left = path.get("left");

      if (left.isIdentifier()) {
        var localName = path.node.name;
        if (localName !== "module" && localName !== "exports") return;
        var localBinding = path.scope.getBinding(localName);
        var rootBinding = this.scope.getBinding(localName);
        if (rootBinding !== localBinding) return;
        var right = path.get("right");
        right.replaceWith(_core.types.sequenceExpression([right.node, getAssertion(localName)]));
      } else if (left.isPattern()) {
        var ids = left.getOuterBindingIdentifiers();
        var _localName = Object.keys(ids).filter(function (localName) {
          if (localName !== "module" && localName !== "exports") return false;
          return _this.scope.getBinding(localName) === path.scope.getBinding(localName);
        })[0];

        if (_localName) {
          var _right = path.get("right");

          _right.replaceWith(_core.types.sequenceExpression([_right.node, getAssertion(_localName)]));
        }
      }
    }
Example #7
0
  function statementList(key, path) {
    var paths = path.get(key);

    for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var _path2 = _ref;
      var func = _path2.node;
      if (!_path2.isFunctionDeclaration()) continue;

      var declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(func.id, _core.types.toExpression(func))]);

      declar._blockHoist = 2;
      func.id = null;

      _path2.replaceWith(declar);
    }
  }
Example #8
0
  function replaceImpureComputedKeys(path) {
    var impureComputedPropertyDeclarators = [];

    for (var _iterator3 = path.get("properties"), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
      var _ref3;

      if (_isArray3) {
        if (_i3 >= _iterator3.length) break;
        _ref3 = _iterator3[_i3++];
      } else {
        _i3 = _iterator3.next();
        if (_i3.done) break;
        _ref3 = _i3.value;
      }

      var _propPath = _ref3;

      var key = _propPath.get("key");

      if (_propPath.node.computed && !key.isPure()) {
        var name = path.scope.generateUidBasedOnNode(key.node);

        var declarator = _core.types.variableDeclarator(_core.types.identifier(name), key.node);

        impureComputedPropertyDeclarators.push(declarator);
        key.replaceWith(_core.types.identifier(name));
      }
    }

    return impureComputedPropertyDeclarators;
  }
Example #9
0
  _proto.buildConstructor = function buildConstructor() {
    var func = _core.types.functionDeclaration(_core.types.cloneNode(this.classRef), [], this.constructorBody);

    _core.types.inherits(func, this.node);

    return func;
  };
Example #10
0
  /**
   * Replace the constructor body of our class.
   */
  function pushConstructor(
    replaceSupers,
    method: { type: "ClassMethod" },
    path: NodePath,
  ) {
    // https://github.com/babel/babel/issues/1077
    if (path.scope.hasOwnBinding(classState.classRef.name)) {
      path.scope.rename(classState.classRef.name);
    }

    setState({
      userConstructorPath: path,
      userConstructor: method,
      hasConstructor: true,
      bareSupers: replaceSupers.bareSupers,
      superReturns: replaceSupers.returns,
    });

    const { construct } = classState;

    t.inheritsComments(construct, method);

    construct.params = method.params;

    t.inherits(construct.body, method.body);
    construct.body.directives = method.body.directives;

    pushConstructorToBody();
  }
Example #11
0
      VariableDeclaration: function VariableDeclaration(path) {
        var node = path.node,
            parent = path.parent,
            scope = path.scope;
        if (!isBlockScoped(node)) return;
        convertBlockScopedToVar(path, null, parent, scope, true);

        if (node._tdzThis) {
          var nodes = [node];

          for (var i = 0; i < node.declarations.length; i++) {
            var decl = node.declarations[i];

            if (decl.init) {
              var assign = _core.types.assignmentExpression("=", decl.id, decl.init);

              assign._ignoreBlockScopingTDZ = true;
              nodes.push(_core.types.expressionStatement(assign));
            }

            decl.init = this.addHelper("temporalUndefined");
          }

          node._blockHoist = 2;

          if (path.isCompletionRecord()) {
            nodes.push(_core.types.expressionStatement(scope.buildUndefinedNode()));
          }

          path.replaceWithMultiple(nodes);
        }
      },
Example #12
0
  run() {
    const block = this.block;
    if (DONE.has(block)) return;
    DONE.add(block);

    const needsClosure = this.getLetReferences();

    // this is a block within a `Function/Program` so we can safely leave it be
    if (t.isFunction(this.parent) || t.isProgram(this.block)) {
      this.updateScopeInfo();
      return;
    }

    // we can skip everything
    if (!this.hasLetReferences) return;

    if (needsClosure) {
      this.wrapClosure();
    } else {
      this.remap();
    }

    this.updateScopeInfo(needsClosure);

    if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) {
      return t.labeledStatement(this.loopLabel, this.loop);
    }
  }
Example #13
0
function loopNodeTo(node) {
  if (t.isBreakStatement(node)) {
    return "break";
  } else if (t.isContinueStatement(node)) {
    return "continue";
  }
}
Example #14
0
  _proto.checkConstants = function checkConstants() {
    var scope = this.scope;
    var state = this.state;

    for (var name in scope.bindings) {
      var binding = scope.bindings[name];
      if (binding.kind !== "const") continue;
      var _arr = binding.constantViolations;

      for (var _i = 0; _i < _arr.length; _i++) {
        var violation = _arr[_i];
        var readOnlyError = state.addHelper("readOnlyError");

        var throwNode = _core.types.callExpression(readOnlyError, [_core.types.stringLiteral(name)]);

        if (violation.isAssignmentExpression()) {
          violation.get("right").replaceWith(_core.types.sequenceExpression([throwNode, violation.get("right").node]));
        } else if (violation.isUpdateExpression()) {
          violation.replaceWith(_core.types.sequenceExpression([throwNode, violation.node]));
        } else if (violation.isForXStatement()) {
          violation.ensureBlock();
          violation.node.body.body.unshift(_core.types.expressionStatement(throwNode));
        }
      }
    }
  };
Example #15
0
  /**
   * Creates a class constructor or bail out if there is none
   */
  function maybeCreateConstructor() {
    let hasConstructor = false;
    const paths = classState.path.get("body.body");
    for (const path of paths) {
      hasConstructor = path.equals("kind", "constructor");
      if (hasConstructor) break;
    }
    if (hasConstructor) return;

    let params, body;

    if (classState.isDerived) {
      const constructor = template.expression.ast`
        (function () {
          super(...arguments);
        })
      `;
      params = constructor.params;
      body = constructor.body;
    } else {
      params = [];
      body = t.blockStatement([]);
    }

    classState.path
      .get("body")
      .unshiftContainer(
        "body",
        t.classMethod("constructor", t.identifier("constructor"), params, body),
      );
  }
Example #16
0
  _proto.run = function run() {
    var block = this.block;
    if (DONE.has(block)) return;
    DONE.add(block);
    var needsClosure = this.getLetReferences();
    this.checkConstants();

    if (_core.types.isFunction(this.parent) || _core.types.isProgram(this.block)) {
      this.updateScopeInfo();
      return;
    }

    if (!this.hasLetReferences) return;

    if (needsClosure) {
      this.wrapClosure();
    } else {
      this.remap();
    }

    this.updateScopeInfo(needsClosure);

    if (this.loopLabel && !_core.types.isLabeledStatement(this.loopParent)) {
      return _core.types.labeledStatement(this.loopLabel, this.loop);
    }
  };
Example #17
0
  _proto.constructorMeMaybe = function constructorMeMaybe() {
    var hasConstructor = false;
    var paths = this.path.get("body.body");
    var _arr = paths;

    for (var _i = 0; _i < _arr.length; _i++) {
      var path = _arr[_i];
      hasConstructor = path.equals("kind", "constructor");
      if (hasConstructor) break;
    }

    if (hasConstructor) return;
    var params, body;

    if (this.isDerived) {
      var _constructor = _core.template.expression.ast(_templateObject);

      params = _constructor.params;
      body = _constructor.body;
    } else {
      params = [];
      body = _core.types.blockStatement([]);
    }

    this.path.get("body").unshiftContainer("body", _core.types.classMethod("constructor", _core.types.identifier("constructor"), params, body));
  };
Example #18
0
  addContinuations(fn) {
    const state = {
      reassignments: {},
      returnStatements: [],
      outsideReferences: this.outsideLetReferences,
    };

    this.scope.traverse(fn, continuationVisitor, state);

    for (let i = 0; i < fn.params.length; i++) {
      const param = fn.params[i];
      if (!state.reassignments[param.name]) continue;

      const newParam = this.scope.generateUidIdentifier(param.name);
      fn.params[i] = newParam;

      this.scope.rename(param.name, newParam.name, fn);

      state.returnStatements.forEach(returnStatement => {
        returnStatement.insertBefore(
          t.expressionStatement(t.assignmentExpression("=", param, newParam)),
        );
      });

      // assign outer reference as it's been modified internally and needs to be retained
      fn.body.body.push(
        t.expressionStatement(t.assignmentExpression("=", param, newParam)),
      );
    }
  }
Example #19
0
export default declare(api => {
  api.assertVersion(7);

  return {
    name: "transform-object-super",

    visitor: {
      ObjectExpression(path, state) {
        let objectRef;
        const getObjectRef = () =>
          (objectRef = objectRef || path.scope.generateUidIdentifier("obj"));

        path.get("properties").forEach(propPath => {
          if (!propPath.isMethod()) return;

          replacePropertySuper(propPath, getObjectRef, state);
        });

        if (objectRef) {
          path.scope.push({ id: t.cloneNode(objectRef) });
          path.replaceWith(
            t.assignmentExpression("=", t.cloneNode(objectRef), path.node),
          );
        }
      },
    },
  };
});
Example #20
0
  checkConstants() {
    const scope = this.scope;
    const state = this.state;

    for (const name in scope.bindings) {
      const binding = scope.bindings[name];
      if (binding.kind !== "const") continue;

      for (const violation of (binding.constantViolations: Array)) {
        const readOnlyError = state.addHelper("readOnlyError");
        const throwNode = t.callExpression(readOnlyError, [
          t.stringLiteral(name),
        ]);

        if (violation.isAssignmentExpression()) {
          violation
            .get("right")
            .replaceWith(
              t.sequenceExpression([throwNode, violation.get("right").node]),
            );
        } else if (violation.isUpdateExpression()) {
          violation.replaceWith(
            t.sequenceExpression([throwNode, violation.node]),
          );
        } else if (violation.isForXStatement()) {
          violation.ensureBlock();
          violation.node.body.body.unshift(t.expressionStatement(throwNode));
        }
      }
    }
  }
Example #21
0
 buildVariableDeclaration(id, init) {
   const declar = t.variableDeclaration("var", [
     t.variableDeclarator(t.cloneNode(id), t.cloneNode(init)),
   ]);
   declar._blockHoist = this.blockHoist;
   return declar;
 }
Example #22
0
    pushObjectPattern(pattern, objRef) {
      // https://github.com/babel/babel/issues/681

      if (!pattern.properties.length) {
        this.nodes.push(
          t.expressionStatement(
            t.callExpression(this.addHelper("objectDestructuringEmpty"), [
              objRef,
            ]),
          ),
        );
      }

      // if we have more than one properties in this pattern and the objectRef is a
      // member expression then we need to assign it to a temporary variable so it's
      // only evaluated once

      if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) {
        const temp = this.scope.generateUidIdentifierBasedOnNode(objRef);
        this.nodes.push(this.buildVariableDeclaration(temp, objRef));
        objRef = temp;
      }

      //

      for (let i = 0; i < pattern.properties.length; i++) {
        const prop = pattern.properties[i];
        if (t.isRestElement(prop)) {
          this.pushObjectRest(pattern, objRef, prop, i);
        } else {
          this.pushObjectProperty(prop, objRef);
        }
      }
    }
Example #23
0
 ExportDefaultDeclaration: function ExportDefaultDeclaration(path) {
   if (!path.get("declaration").isClassDeclaration()) return;
   var node = path.node;
   var ref = node.declaration.id || path.scope.generateUidIdentifier("class");
   node.declaration.id = ref;
   path.replaceWith(node.declaration);
   path.insertAfter(_core.types.exportNamedDeclaration(null, [_core.types.exportSpecifier(_core.types.cloneNode(ref), _core.types.identifier("default"))]));
 },
Example #24
0
 globalToAssign = members.slice(1).reduce((accum, curr) => {
   initAssignments.push(
     buildPrerequisiteAssignment({
       GLOBAL_REFERENCE: t.cloneNode(accum),
     }),
   );
   return t.memberExpression(accum, t.identifier(curr));
 }, t.memberExpression(t.identifier("global"), t.identifier(members[0])));
Example #25
0
 function buildExportCall(name, val) {
   return t.expressionStatement(
     t.callExpression(t.identifier(exportIdent), [
       t.stringLiteral(name),
       val,
     ]),
   );
 }
Example #26
0
 /**
  * Helper function to run a statement before an expression by replacing it with a comma expression
  * and wrapping the statement in an IIFE as the first operand.
  */
 function statementBeforeExpression(statement, expression) {
   return t.sequenceExpression([
     t.callExpression(
       t.functionExpression(null, [], t.blockStatement([statement])),
       [],
     ),
     expression,
   ]);
 }
Example #27
0
 wrapReturn = returnArg => {
   const thisExpr = t.callExpression(
     classState.file.addHelper("assertThisInitialized"),
     [thisRef()],
   );
   return returnArg
     ? t.logicalExpression("||", returnArg, thisExpr)
     : thisExpr;
 };
Example #28
0
function buildConstructor(classRef, constructorBody, node) {
  const func = t.functionDeclaration(
    t.cloneNode(classRef),
    [],
    constructorBody,
  );
  t.inherits(func, node);
  return func;
}
Example #29
0
 var buildClassPropertyLoose = function buildClassPropertyLoose(ref, _ref2, scope) {
   var key = _ref2.key,
       value = _ref2.value,
       computed = _ref2.computed;
   return _core.template.statement(_templateObject2)({
     MEMBER: _core.types.memberExpression(_core.types.cloneNode(ref), key, computed || _core.types.isLiteral(key)),
     VALUE: value || scope.buildUndefinedNode()
   });
 };
Example #30
-1
    _proto.pushObjectRest = function pushObjectRest(pattern, objRef, spreadProp, spreadPropIndex) {
      var keys = [];

      for (var i = 0; i < pattern.properties.length; i++) {
        var prop = pattern.properties[i];
        if (i >= spreadPropIndex) break;
        if (_core.types.isRestElement(prop)) continue;
        var key = prop.key;

        if (_core.types.isIdentifier(key) && !prop.computed) {
          key = _core.types.stringLiteral(prop.key.name);
        }

        keys.push(_core.types.cloneNode(key));
      }

      var value;

      if (keys.length === 0) {
        value = _core.types.callExpression(getExtendsHelper(this), [_core.types.objectExpression([]), _core.types.cloneNode(objRef)]);
      } else {
        keys = _core.types.arrayExpression(keys);
        value = _core.types.callExpression(this.addHelper("objectWithoutProperties"), [_core.types.cloneNode(objRef), keys]);
      }

      this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value));
    };