Java Code Examples for com.google.javascript.rhino.Node#isFor()

The following examples show how to use com.google.javascript.rhino.Node#isFor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Cardumen_0092_t.java    From coming with MIT License 6 votes vote down vote up
private void addSimplifiedExpression(Node n, Node parent) {
  if (parent.isVar()) {
    Node value = n.getFirstChild();
    if (value != null) {
      addSimplifiedChildren(value);
    }
  } else if (n.isAssign() &&
      (parent.isExprResult() ||
       parent.isFor() ||
       parent.isReturn())) {
    for (Node child : n.children()) {
      addSimplifiedChildren(child);
    }
  } else if (n.isCall() &&
             parent.isExprResult()) {
    addSimplifiedChildren(n);
  } else {
    addAllChildren(n);
  }
}
 
Example 2
Source File: Cardumen_0092_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace n with a simpler expression, while preserving program
 * behavior.
 *
 * If the n's value is used, replace it with its rhs; otherwise
 * replace it with the subexpressions that have side effects.
 */
private void replaceWithRhs(Node parent, Node n) {
  if (valueConsumedByParent(n, parent)) {
    // parent reads from n directly; replace it with n's rhs + lhs
    // subexpressions with side effects.
    List<Node> replacements = getRhsSubexpressions(n);
    List<Node> newReplacements = Lists.newArrayList();
    for (int i = 0; i < replacements.size() - 1; i++) {
      newReplacements.addAll(getSideEffectNodes(replacements.get(i)));
    }
    Node valueExpr = replacements.get(replacements.size() - 1);
    valueExpr.detachFromParent();
    newReplacements.add(valueExpr);
    changeProxy.replaceWith(
        parent, n, collapseReplacements(newReplacements));
  } else if (n.isAssign() && !parent.isFor()) {
    // assignment appears in a RHS expression.  we have already
    // considered names in the assignment's RHS as being referenced;
    // replace the assignment with its RHS.
    // TODO(user) make the pass smarter about these cases and/or run
    // this pass and RemoveConstantExpressions together in a loop.
    Node replacement = n.getLastChild();
    replacement.detachFromParent();
    changeProxy.replaceWith(parent, n, replacement);
  } else {
    replaceTopLevelExpressionWithRhs(parent, n);
  }
}
 
Example 3
Source File: Closure_114_NameAnalyzer_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace n with a simpler expression, while preserving program
 * behavior.
 *
 * If the n's value is used, replace it with its RHS; otherwise
 * replace it with the subexpressions that have side effects.
 */
private void replaceWithRhs(Node parent, Node n) {
  if (valueConsumedByParent(n, parent)) {
    // parent reads from n directly; replace it with n's rhs + lhs
    // subexpressions with side effects.
    List<Node> replacements = getRhsSubexpressions(n);
    List<Node> newReplacements = Lists.newArrayList();
    for (int i = 0; i < replacements.size() - 1; i++) {
      newReplacements.addAll(getSideEffectNodes(replacements.get(i)));
    }
    Node valueExpr = replacements.get(replacements.size() - 1);
    valueExpr.detachFromParent();
    newReplacements.add(valueExpr);
    changeProxy.replaceWith(
        parent, n, collapseReplacements(newReplacements));
  } else if (n.isAssign() && !parent.isFor()) {
    // assignment appears in a RHS expression.  we have already
    // considered names in the assignment's RHS as being referenced;
    // replace the assignment with its RHS.
    // TODO(user) make the pass smarter about these cases and/or run
    // this pass and RemoveConstantExpressions together in a loop.
    Node replacement = n.getLastChild();
    replacement.detachFromParent();
    changeProxy.replaceWith(parent, n, replacement);
  } else {
    replaceTopLevelExpressionWithRhs(parent, n);
  }
}
 
Example 4
Source File: CoalesceVariableNames.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tries to remove variable declaration if the variable has been coalesced
 * with another variable that has already been declared.
 */
private void removeVarDeclaration(Node name) {
  Node var = name.getParent();
  Node parent = var.getParent();

  // Special case when we are in FOR-IN loop.
  if (NodeUtil.isForIn(parent)) {
    var.removeChild(name);
    parent.replaceChild(var, name);
  } else if (var.hasOneChild()) {
    // The removal is easy when there is only one variable in the VAR node.
    if (name.hasChildren()) {
      Node value = name.removeFirstChild();
      var.removeChild(name);
      Node assign = IR.assign(name, value).srcref(name);

      // We don't need to wrapped it with EXPR node if it is within a FOR.
      if (!parent.isFor()) {
        assign = NodeUtil.newExpr(assign);
      }
      parent.replaceChild(var, assign);

    } else {
      // In a FOR( ; ; ) node, we must replace it with an EMPTY or else it
      // becomes a FOR-IN node.
      NodeUtil.removeChild(parent, var);
    }
  } else {
    if (!name.hasChildren()) {
      var.removeChild(name);
    }
    // We are going to leave duplicated declaration otherwise.
  }
}
 
Example 5
Source File: Closure_40_NameAnalyzer_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace n with a simpler expression, while preserving program
 * behavior.
 *
 * If the n's value is used, replace it with its rhs; otherwise
 * replace it with the subexpressions that have side effects.
 */
private void replaceWithRhs(Node parent, Node n) {
  if (valueConsumedByParent(n, parent)) {
    // parent reads from n directly; replace it with n's rhs + lhs
    // subexpressions with side effects.
    List<Node> replacements = getRhsSubexpressions(n);
    List<Node> newReplacements = Lists.newArrayList();
    for (int i = 0; i < replacements.size() - 1; i++) {
      newReplacements.addAll(getSideEffectNodes(replacements.get(i)));
    }
    Node valueExpr = replacements.get(replacements.size() - 1);
    valueExpr.detachFromParent();
    newReplacements.add(valueExpr);
    changeProxy.replaceWith(
        parent, n, collapseReplacements(newReplacements));
  } else if (n.isAssign() && !parent.isFor()) {
    // assignment appears in a RHS expression.  we have already
    // considered names in the assignment's RHS as being referenced;
    // replace the assignment with its RHS.
    // TODO(user) make the pass smarter about these cases and/or run
    // this pass and RemoveConstantExpressions together in a loop.
    Node replacement = n.getLastChild();
    replacement.detachFromParent();
    changeProxy.replaceWith(parent, n, replacement);
  } else {
    replaceTopLevelExpressionWithRhs(parent, n);
  }
}
 
Example 6
Source File: NameAnalyzer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Replace n with a simpler expression, while preserving program
 * behavior.
 *
 * If the n's value is used, replace it with its RHS; otherwise
 * replace it with the subexpressions that have side effects.
 */
private void replaceWithRhs(Node parent, Node n) {
  if (valueConsumedByParent(n, parent)) {
    // parent reads from n directly; replace it with n's rhs + lhs
    // subexpressions with side effects.
    List<Node> replacements = getRhsSubexpressions(n);
    List<Node> newReplacements = Lists.newArrayList();
    for (int i = 0; i < replacements.size() - 1; i++) {
      newReplacements.addAll(getSideEffectNodes(replacements.get(i)));
    }
    Node valueExpr = replacements.get(replacements.size() - 1);
    valueExpr.detachFromParent();
    newReplacements.add(valueExpr);
    changeProxy.replaceWith(
        parent, n, collapseReplacements(newReplacements));
  } else if (n.isAssign() && !parent.isFor()) {
    // assignment appears in a RHS expression.  we have already
    // considered names in the assignment's RHS as being referenced;
    // replace the assignment with its RHS.
    // TODO(user) make the pass smarter about these cases and/or run
    // this pass and RemoveConstantExpressions together in a loop.
    Node replacement = n.getLastChild();
    replacement.detachFromParent();
    changeProxy.replaceWith(parent, n, replacement);
  } else {
    replaceTopLevelExpressionWithRhs(parent, n);
  }
}
 
Example 7
Source File: Cardumen_0020_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace n with a simpler expression, while preserving program
 * behavior.
 *
 * If the n's value is used, replace it with its rhs; otherwise
 * replace it with the subexpressions that have side effects.
 */
private void replaceWithRhs(Node parent, Node n) {
  if (valueConsumedByParent(n, parent)) {
    // parent reads from n directly; replace it with n's rhs + lhs
    // subexpressions with side effects.
    List<Node> replacements = getRhsSubexpressions(n);
    List<Node> newReplacements = Lists.newArrayList();
    for (int i = 0; i < replacements.size() - 1; i++) {
      newReplacements.addAll(getSideEffectNodes(replacements.get(i)));
    }
    Node valueExpr = replacements.get(replacements.size() - 1);
    valueExpr.detachFromParent();
    newReplacements.add(valueExpr);
    changeProxy.replaceWith(
        parent, n, collapseReplacements(newReplacements));
  } else if (n.isAssign() && !parent.isFor()) {
    // assignment appears in a RHS expression.  we have already
    // considered names in the assignment's RHS as being referenced;
    // replace the assignment with its RHS.
    // TODO(user) make the pass smarter about these cases and/or run
    // this pass and RemoveConstantExpressions together in a loop.
    Node replacement = n.getLastChild();
    replacement.detachFromParent();
    changeProxy.replaceWith(parent, n, replacement);
  } else {
    replaceTopLevelExpressionWithRhs(parent, n);
  }
}
 
Example 8
Source File: Cardumen_0092_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Simplify a toplevel expression, while preserving program
 * behavior.
 */
private void replaceTopLevelExpressionWithRhs(Node parent, Node n) {
  // validate inputs
  switch (parent.getType()) {
    case Token.BLOCK:
    case Token.SCRIPT:
    case Token.FOR:
    case Token.LABEL:
      break;
    default:
      throw new IllegalArgumentException(
          "Unsupported parent node type in replaceWithRhs " +
          Token.name(parent.getType()));
  }

  switch (n.getType()) {
    case Token.EXPR_RESULT:
    case Token.FUNCTION:
    case Token.VAR:
      break;
    case Token.ASSIGN:
      Preconditions.checkArgument(parent.isFor(),
          "Unsupported assignment in replaceWithRhs. parent: %s", Token.name(parent.getType()));
      break;
    default:
      throw new IllegalArgumentException(
          "Unsupported node type in replaceWithRhs " +
          Token.name(n.getType()));
  }

  // gather replacements
  List<Node> replacements = Lists.newArrayList();
  for (Node rhs : getRhsSubexpressions(n)) {
    replacements.addAll(getSideEffectNodes(rhs));
  }

  if (parent.isFor()) {
    // tweak replacements array s.t. it is a single expression node.
    if (replacements.isEmpty()) {
      replacements.add(IR.empty());
    } else {
      Node expr = collapseReplacements(replacements);
      replacements.clear();
      replacements.add(expr);
    }
  }

  changeProxy.replaceWith(parent, n, replacements);
}
 
Example 9
Source File: Cardumen_0021_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Removes any vars in the scope that were not referenced. Removes any
 * assignments to those variables as well.
 */
private void removeUnreferencedVars() {
  CodingConvention convention = codingConvention;

  for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
    Var var = it.next();

    // Remove calls to inheritance-defining functions where the unreferenced
    // class is the subclass.
    for (Node exprCallNode : inheritsCalls.get(var)) {
      NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
      compiler.reportCodeChange();
    }

    // Regardless of what happens to the original declaration,
    // we need to remove all assigns, because they may contain references
    // to other unreferenced variables.
    removeAllAssigns(var);

    compiler.addToDebugLog("Unreferenced var: " + var.name);
    Node nameNode = var.nameNode;
    Node toRemove = nameNode.getParent();
    Node parent = toRemove.getParent();

    Preconditions.checkState(
        toRemove.isVar() ||
        toRemove.isFunction() ||
        toRemove.isParamList() &&
        parent.isFunction(),
        "We should only declare vars and functions and function args");

    if (toRemove.isParamList() &&
        parent.isFunction()) {
      // Don't remove function arguments here. That's a special case
      // that's taken care of in removeUnreferencedFunctionArgs.
    } else if (NodeUtil.isFunctionExpression(toRemove)) {
      if (!preserveFunctionExpressionNames) {
        toRemove.getFirstChild().setString("");
        compiler.reportCodeChange();
      }
      // Don't remove bleeding functions.
    } else if (parent != null &&
        parent.isFor() &&
        parent.getChildCount() < 4) {
      // foreach iterations have 3 children. Leave them alone.
    } else if (toRemove.isVar() &&
        nameNode.hasChildren() &&
        NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
      // If this is a single var declaration, we can at least remove the
      // declaration itself and just leave the value, e.g.,
      // var a = foo(); => foo();
      if (toRemove.getChildCount() == 1) {
        parent.replaceChild(toRemove,
            IR.exprResult(nameNode.removeFirstChild()));
        compiler.reportCodeChange();
      }
    } else if (toRemove.isVar() &&
        toRemove.getChildCount() > 1) {
      // For var declarations with multiple names (i.e. var a, b, c),
      // only remove the unreferenced name
      toRemove.removeChild(nameNode);
      compiler.reportCodeChange();
    } else if (parent != null) {
      NodeUtil.removeChild(parent, toRemove);
      compiler.reportCodeChange();
    }
  }
}
 
Example 10
Source File: jMutRepair_003_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node represents a FOR-IN loop.
 */
static boolean isForIn(Node n) {
  return n.isFor()
      && n.getChildCount() == 3;
}
 
Example 11
Source File: Cardumen_00152_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Removes any vars in the scope that were not referenced. Removes any
 * assignments to those variables as well.
 */
private void removeUnreferencedVars() {
  CodingConvention convention = codingConvention;

  for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
    Var var = it.next();

    // Remove calls to inheritance-defining functions where the unreferenced
    // class is the subclass.
    for (Node exprCallNode : inheritsCalls.get(var)) {
      NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
      compiler.reportCodeChange();
    }

    // Regardless of what happens to the original declaration,
    // we need to remove all assigns, because they may contain references
    // to other unreferenced variables.
    removeAllAssigns(var);

    compiler.addToDebugLog("Unreferenced var: " + var.name);
    Node nameNode = var.nameNode;
    Node toRemove = nameNode.getParent();
    Node parent = toRemove.getParent();

    Preconditions.checkState(
        toRemove.isVar() ||
        toRemove.isFunction() ||
        toRemove.isParamList() &&
        parent.isFunction(),
        "We should only declare vars and functions and function args");

    if (toRemove.isParamList() &&
        parent.isFunction()) {
      // Don't remove function arguments here. That's a special case
      // that's taken care of in removeUnreferencedFunctionArgs.
    } else if (NodeUtil.isFunctionExpression(toRemove)) {
      if (!preserveFunctionExpressionNames) {
        toRemove.getFirstChild().setString("");
        compiler.reportCodeChange();
      }
      // Don't remove bleeding functions.
    } else if (parent != null &&
        parent.isFor() &&
        parent.getChildCount() < 4) {
      // foreach iterations have 3 children. Leave them alone.
    } else if (toRemove.isVar() &&
        nameNode.hasChildren() &&
        NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
      // If this is a single var declaration, we can at least remove the
      // declaration itself and just leave the value, e.g.,
      // var a = foo(); => foo();
      if (toRemove.getChildCount() == 1) {
        parent.replaceChild(toRemove,
            IR.exprResult(nameNode.removeFirstChild()));
        compiler.reportCodeChange();
      }
    } else if (toRemove.isVar() &&
        toRemove.getChildCount() > 1) {
      // For var declarations with multiple names (i.e. var a, b, c),
      // only remove the unreferenced name
      toRemove.removeChild(nameNode);
      compiler.reportCodeChange();
    } else if (parent != null) {
      NodeUtil.removeChild(parent, toRemove);
      compiler.reportCodeChange();
    }
  }
}
 
Example 12
Source File: Cardumen_00203_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Removes any vars in the scope that were not referenced. Removes any
 * assignments to those variables as well.
 */
private void removeUnreferencedVars() {
  CodingConvention convention = codingConvention;

  for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
    Var var = it.next();

    // Remove calls to inheritance-defining functions where the unreferenced
    // class is the subclass.
    for (Node exprCallNode : inheritsCalls.get(var)) {
      NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
      compiler.reportCodeChange();
    }

    // Regardless of what happens to the original declaration,
    // we need to remove all assigns, because they may contain references
    // to other unreferenced variables.
    removeAllAssigns(var);

    compiler.addToDebugLog("Unreferenced var: " + var.name);
    Node nameNode = var.nameNode;
    Node toRemove = nameNode.getParent();
    Node parent = toRemove.getParent();

    Preconditions.checkState(
        toRemove.isVar() ||
        toRemove.isFunction() ||
        toRemove.isParamList() &&
        parent.isFunction(),
        "We should only declare vars and functions and function args");

    if (toRemove.isParamList() &&
        parent.isFunction()) {
      // Don't remove function arguments here. That's a special case
      // that's taken care of in removeUnreferencedFunctionArgs.
    } else if (NodeUtil.isFunctionExpression(toRemove)) {
      if (!preserveFunctionExpressionNames) {
        toRemove.getFirstChild().setString("");
        compiler.reportCodeChange();
      }
      // Don't remove bleeding functions.
    } else if (parent != null &&
        parent.isFor() &&
        parent.getChildCount() < 4) {
      // foreach iterations have 3 children. Leave them alone.
    } else if (toRemove.isVar() &&
        nameNode.hasChildren() &&
        NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
      // If this is a single var declaration, we can at least remove the
      // declaration itself and just leave the value, e.g.,
      // var a = foo(); => foo();
      if (toRemove.getChildCount() == 1) {
        parent.replaceChild(toRemove,
            IR.exprResult(nameNode.removeFirstChild()));
        compiler.reportCodeChange();
      }
    } else if (toRemove.isVar() &&
        toRemove.getChildCount() > 1) {
      // For var declarations with multiple names (i.e. var a, b, c),
      // only remove the unreferenced name
      toRemove.removeChild(nameNode);
      compiler.reportCodeChange();
    } else if (parent != null) {
      NodeUtil.removeChild(parent, toRemove);
      compiler.reportCodeChange();
    }
  }
}
 
Example 13
Source File: RemoveUnusedVars.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Removes any vars in the scope that were not referenced. Removes any
 * assignments to those variables as well.
 */
private void removeUnreferencedVars() {
  CodingConvention convention = codingConvention;

  for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
    Var var = it.next();

    // Remove calls to inheritance-defining functions where the unreferenced
    // class is the subclass.
    for (Node exprCallNode : classDefiningCalls.get(var)) {
      NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
      compiler.reportCodeChange();
    }

    // Regardless of what happens to the original declaration,
    // we need to remove all assigns, because they may contain references
    // to other unreferenced variables.
    removeAllAssigns(var);

    compiler.addToDebugLog("Unreferenced var: " + var.name);
    Node nameNode = var.nameNode;
    Node toRemove = nameNode.getParent();
    Node parent = toRemove.getParent();

    Preconditions.checkState(
        toRemove.isVar() ||
        toRemove.isFunction() ||
        toRemove.isParamList() &&
        parent.isFunction(),
        "We should only declare vars and functions and function args");

    if (toRemove.isParamList() &&
        parent.isFunction()) {
      // Don't remove function arguments here. That's a special case
      // that's taken care of in removeUnreferencedFunctionArgs.
    } else if (NodeUtil.isFunctionExpression(toRemove)) {
      if (!preserveFunctionExpressionNames) {
        toRemove.getFirstChild().setString("");
        compiler.reportCodeChange();
      }
      // Don't remove bleeding functions.
    } else if (parent != null &&
        parent.isFor() &&
        parent.getChildCount() < 4) {
      // foreach iterations have 3 children. Leave them alone.
    } else if (toRemove.isVar() &&
        nameNode.hasChildren() &&
        NodeUtil.mayHaveSideEffects(nameNode.getFirstChild(), compiler)) {
      // If this is a single var declaration, we can at least remove the
      // declaration itself and just leave the value, e.g.,
      // var a = foo(); => foo();
      if (toRemove.getChildCount() == 1) {
        parent.replaceChild(toRemove,
            IR.exprResult(nameNode.removeFirstChild()));
        compiler.reportCodeChange();
      }
    } else if (toRemove.isVar() &&
        toRemove.getChildCount() > 1) {
      // For var declarations with multiple names (i.e. var a, b, c),
      // only remove the unreferenced name
      toRemove.removeChild(nameNode);
      compiler.reportCodeChange();
    } else if (parent != null) {
      NodeUtil.removeChild(parent, toRemove);
      compiler.reportCodeChange();
    }
  }
}
 
Example 14
Source File: Closure_10_NodeUtil_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node represents a FOR-IN loop.
 */
static boolean isForIn(Node n) {
  return n.isFor()
      && n.getChildCount() == 3;
}
 
Example 15
Source File: Closure_45_RemoveUnusedVars_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Removes any vars in the scope that were not referenced. Removes any
 * assignments to those variables as well.
 */
private void removeUnreferencedVars() {
  CodingConvention convention = codingConvention;

  for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
    Var var = it.next();

    // Remove calls to inheritance-defining functions where the unreferenced
    // class is the subclass.
    for (Node exprCallNode : inheritsCalls.get(var)) {
      NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
      compiler.reportCodeChange();
    }

    // Regardless of what happens to the original declaration,
    // we need to remove all assigns, because they may contain references
    // to other unreferenced variables.
    removeAllAssigns(var);

    compiler.addToDebugLog("Unreferenced var: " + var.name);
    Node nameNode = var.nameNode;
    Node toRemove = nameNode.getParent();
    Node parent = toRemove.getParent();

    Preconditions.checkState(
        toRemove.isVar() ||
        toRemove.isFunction() ||
        toRemove.isParamList() &&
        parent.isFunction(),
        "We should only declare vars and functions and function args");

    if (toRemove.isParamList() &&
        parent.isFunction()) {
      // Don't remove function arguments here. That's a special case
      // that's taken care of in removeUnreferencedFunctionArgs.
    } else if (NodeUtil.isFunctionExpression(toRemove)) {
      if (!preserveFunctionExpressionNames) {
        toRemove.getFirstChild().setString("");
        compiler.reportCodeChange();
      }
      // Don't remove bleeding functions.
    } else if (parent != null &&
        parent.isFor() &&
        parent.getChildCount() < 4) {
      // foreach iterations have 3 children. Leave them alone.
    } else if (toRemove.isVar() &&
        nameNode.hasChildren() &&
        NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
      // If this is a single var declaration, we can at least remove the
      // declaration itself and just leave the value, e.g.,
      // var a = foo(); => foo();
      if (toRemove.getChildCount() == 1) {
        parent.replaceChild(toRemove,
            IR.exprResult(nameNode.removeFirstChild()));
        compiler.reportCodeChange();
      }
    } else if (toRemove.isVar() &&
        toRemove.getChildCount() > 1) {
      // For var declarations with multiple names (i.e. var a, b, c),
      // only remove the unreferenced name
      toRemove.removeChild(nameNode);
      compiler.reportCodeChange();
    } else if (parent != null) {
      NodeUtil.removeChild(parent, toRemove);
      compiler.reportCodeChange();
    }
  }
}
 
Example 16
Source File: jMutRepair_003_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node represents a FOR-IN loop.
 */
static boolean isForIn(Node n) {
  return n.isFor()
      && n.getChildCount() == 3;
}
 
Example 17
Source File: Closure_45_RemoveUnusedVars_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Removes any vars in the scope that were not referenced. Removes any
 * assignments to those variables as well.
 */
private void removeUnreferencedVars() {
  CodingConvention convention = codingConvention;

  for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
    Var var = it.next();

    // Remove calls to inheritance-defining functions where the unreferenced
    // class is the subclass.
    for (Node exprCallNode : inheritsCalls.get(var)) {
      NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
      compiler.reportCodeChange();
    }

    // Regardless of what happens to the original declaration,
    // we need to remove all assigns, because they may contain references
    // to other unreferenced variables.
    removeAllAssigns(var);

    compiler.addToDebugLog("Unreferenced var: " + var.name);
    Node nameNode = var.nameNode;
    Node toRemove = nameNode.getParent();
    Node parent = toRemove.getParent();

    Preconditions.checkState(
        toRemove.isVar() ||
        toRemove.isFunction() ||
        toRemove.isParamList() &&
        parent.isFunction(),
        "We should only declare vars and functions and function args");

    if (toRemove.isParamList() &&
        parent.isFunction()) {
      // Don't remove function arguments here. That's a special case
      // that's taken care of in removeUnreferencedFunctionArgs.
    } else if (NodeUtil.isFunctionExpression(toRemove)) {
      if (!preserveFunctionExpressionNames) {
        toRemove.getFirstChild().setString("");
        compiler.reportCodeChange();
      }
      // Don't remove bleeding functions.
    } else if (parent != null &&
        parent.isFor() &&
        parent.getChildCount() < 4) {
      // foreach iterations have 3 children. Leave them alone.
    } else if (toRemove.isVar() &&
        nameNode.hasChildren() &&
        NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
      // If this is a single var declaration, we can at least remove the
      // declaration itself and just leave the value, e.g.,
      // var a = foo(); => foo();
      if (toRemove.getChildCount() == 1) {
        parent.replaceChild(toRemove,
            IR.exprResult(nameNode.removeFirstChild()));
        compiler.reportCodeChange();
      }
    } else if (toRemove.isVar() &&
        toRemove.getChildCount() > 1) {
      // For var declarations with multiple names (i.e. var a, b, c),
      // only remove the unreferenced name
      toRemove.removeChild(nameNode);
      compiler.reportCodeChange();
    } else if (parent != null) {
      NodeUtil.removeChild(parent, toRemove);
      compiler.reportCodeChange();
    }
  }
}
 
Example 18
Source File: GroupVariableDeclarations.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Attempts to collapse groupVar. This can only happen if groupVar has at most
 * one variable initialization (it may have multiple variable declarations).
 * If successful, then detaches groupVar's children and appends them to
 * firstVar
 *
 * @param firstVar The first VAR {@code Node} in that scope. This is the node
 *                 that we want to collapse groupVar into
 * @param groupVar The VAR {@code Node} that we want to try collapsing
 *                 into the first VAR node of that scope
 */
private void applyGroupingToVar(Node firstVar, Node groupVar) {
  Node child = groupVar.getFirstChild();
  // if some variable is initialized, then the corresponding NAME node will be
  // stored here
  Node initializedName = null;
  while (child != null) {
    if (child.hasChildren()) {
      // check that no more than one var is initialized
      if (initializedName != null) {
        return;
      }
      initializedName = child;
    }
    child = child.getNext();
  }

  // we will be modifying the groupVar subtree so get its parent
  Node groupVarParent = groupVar.getParent();


  if (initializedName != null) {
    if (NodeUtil.isForIn(groupVarParent)) {
      // The target of the for-in expression must be an assignable expression.
      return;
    }

    // we have an initialized var in the VAR node. We will replace the
    // VAR node with an assignment.

    // first create a detached childless clone of initializedName.
    Node clone = initializedName.cloneNode();
    // replace
    groupVar.replaceChild(initializedName, clone);
    // add the assignment now.
    Node initializedVal = initializedName.removeFirstChild();
    Node assignmentNode = IR.assign(initializedName, initializedVal);
    if (groupVarParent.isFor()) {
      // Handle For and For-In Loops specially. For these, we do not need
      // to construct an EXPR_RESULT node.
      groupVarParent.replaceChild(groupVar, assignmentNode);
    } else {
      Node exprNode = NodeUtil.newExpr(assignmentNode);
      groupVarParent.replaceChild(groupVar, exprNode);
    }
  } else {
    // There is no initialized var. But we need to handle FOR and
    // FOR-IN loops specially
    if (groupVarParent.isFor()) {
      if (NodeUtil.isForIn(groupVarParent)) {
        // In For-In loop, we replace the VAR node with a NAME node
        Node nameNodeClone = groupVar.getFirstChild().cloneNode();
        groupVarParent.replaceChild(groupVar, nameNodeClone);
      } else {
        // In For loop, we replace the VAR node with an EMPTY node
        Node emptyNode = IR.empty();
        groupVarParent.replaceChild(groupVar, emptyNode);
      }
    } else {
      // we can safely remove the VAR node
      groupVarParent.removeChild(groupVar);
    }
  }

  Node children = groupVar.removeChildren();
  firstVar.addChildrenToBack(children);

  compiler.reportCodeChange();
}
 
Example 19
Source File: Cardumen_00149_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node represents a FOR-IN loop.
 */
static boolean isForIn(Node n) {
  return n.isFor()
      && n.getChildCount() == 3;
}
 
Example 20
Source File: Closure_40_NameAnalyzer_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Simplify a toplevel expression, while preserving program
 * behavior.
 */
private void replaceTopLevelExpressionWithRhs(Node parent, Node n) {
  // validate inputs
  switch (parent.getType()) {
    case Token.BLOCK:
    case Token.SCRIPT:
    case Token.FOR:
    case Token.LABEL:
      break;
    default:
      throw new IllegalArgumentException(
          "Unsupported parent node type in replaceWithRhs " +
          Token.name(parent.getType()));
  }

  switch (n.getType()) {
    case Token.EXPR_RESULT:
    case Token.FUNCTION:
    case Token.VAR:
      break;
    case Token.ASSIGN:
      Preconditions.checkArgument(parent.isFor(),
          "Unsupported assignment in replaceWithRhs. parent: %s", Token.name(parent.getType()));
      break;
    default:
      throw new IllegalArgumentException(
          "Unsupported node type in replaceWithRhs " +
          Token.name(n.getType()));
  }

  // gather replacements
  List<Node> replacements = Lists.newArrayList();
  for (Node rhs : getRhsSubexpressions(n)) {
    replacements.addAll(getSideEffectNodes(rhs));
  }

  if (parent.isFor()) {
    // tweak replacements array s.t. it is a single expression node.
    if (replacements.isEmpty()) {
      replacements.add(IR.empty());
    } else {
      Node expr = collapseReplacements(replacements);
      replacements.clear();
      replacements.add(expr);
    }
  }

  changeProxy.replaceWith(parent, n, replacements);
}