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

The following examples show how to use com.google.javascript.rhino.Node#removeFirstChild() . 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: Closure_80_NodeUtil_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Merge a block with its parent block.
 * @return Whether the block was removed.
 */
static boolean tryMergeBlock(Node block) {
  Preconditions.checkState(block.getType() == Token.BLOCK);
  Node parent = block.getParent();
  // Try to remove the block if its parent is a block/script or if its
  // parent is label and it has exactly one child.
  if (isStatementBlock(parent)) {
    Node previous = block;
    while (block.hasChildren()) {
      Node child = block.removeFirstChild();
      parent.addChildAfter(child, previous);
      previous = child;
    }
    parent.removeChild(block);
    return true;
  } else {
    return false;
  }
}
 
Example 2
Source File: Closure_75_NodeUtil_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Merge a block with its parent block.
 * @return Whether the block was removed.
 */
static boolean tryMergeBlock(Node block) {
  Preconditions.checkState(block.getType() == Token.BLOCK);
  Node parent = block.getParent();
  // Try to remove the block if its parent is a block/script or if its
  // parent is label and it has exactly one child.
  if (isStatementBlock(parent)) {
    Node previous = block;
    while (block.hasChildren()) {
      Node child = block.removeFirstChild();
      parent.addChildAfter(child, previous);
      previous = child;
    }
    parent.removeChild(block);
    return true;
  } else {
    return false;
  }
}
 
Example 3
Source File: TypeConversionPass.java    From clutz with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  switch (n.getToken()) {
    case VAR:
    case LET:
    case CONST:
      if (n.getJSDocInfo() == null || n.getJSDocInfo().getEnumParameterType() == null) return;
      JSTypeExpression enumExp = n.getJSDocInfo().getEnumParameterType();
      if (!enumExp.getRoot().isString()) return;
      String enumTypeStr = enumExp.getRoot().getString();
      if (!enumTypeStr.equals("number") && !enumTypeStr.equals("string")) return;

      Node name = n.removeFirstChild();
      Node members = name.removeFirstChild();

      Node enumMembers = transformMembers(members, enumTypeStr.equals("number"));
      Node enumNode = new Node(Token.ENUM, name, enumMembers);
      parent.replaceChild(n, enumNode);
      compiler.reportChangeToEnclosingScope(parent);
      break;
    default:
      break;
  }
}
 
Example 4
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Reduce "return undefined" or "return void 0" to simply "return".
 */
private void tryReduceReturn(NodeTraversal t, Node n) {
  Node result = n.getFirstChild();
  if (result != null) {
    switch (result.getType()) {
      case Token.VOID:
        Node operand = result.getFirstChild();
        if (!NodeUtil.mayHaveSideEffects(operand)) {
          n.removeFirstChild();
          t.getCompiler().reportCodeChange();
        }
        return;
      case Token.NAME:
        String name = result.getString();
        if (name.equals("undefined")) {
          n.removeFirstChild();
          t.getCompiler().reportCodeChange();
        }
        return;
    }
  }
}
 
Example 5
Source File: jMutRepair_003_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Merge a block with its parent block.
 * @return Whether the block was removed.
 */
static boolean tryMergeBlock(Node block) {
  Preconditions.checkState(block.isBlock());
  Node parent = block.getParent();
  // Try to remove the block if its parent is a block/script or if its
  // parent is label and it has exactly one child.
  if (isStatementBlock(parent)) {
    Node previous = block;
    while (block.hasChildren()) {
      Node child = block.removeFirstChild();
      parent.addChildAfter(child, previous);
      previous = child;
    }
    parent.removeChild(block);
    return true;
  } else {
    return false;
  }
}
 
Example 6
Source File: Closure_20_PeepholeSubstituteAlternateSyntax_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Reduce "return undefined" or "return void 0" to simply "return".
 *
 * @return The original node, maybe simplified.
 */
private Node tryReduceReturn(Node n) {
  Node result = n.getFirstChild();

  if (result != null) {
    switch (result.getType()) {
      case Token.VOID:
        Node operand = result.getFirstChild();
        if (!mayHaveSideEffects(operand)) {
          n.removeFirstChild();
          reportCodeChange();
        }
        break;
      case Token.NAME:
        String name = result.getString();
        if (name.equals("undefined")) {
          n.removeFirstChild();
          reportCodeChange();
        }
        break;
    }
  }

  return n;
}
 
Example 7
Source File: Closure_61_NodeUtil_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Merge a block with its parent block.
 * @return Whether the block was removed.
 */
static boolean tryMergeBlock(Node block) {
  Preconditions.checkState(block.getType() == Token.BLOCK);
  Node parent = block.getParent();
  // Try to remove the block if its parent is a block/script or if its
  // parent is label and it has exactly one child.
  if (isStatementBlock(parent)) {
    Node previous = block;
    while (block.hasChildren()) {
      Node child = block.removeFirstChild();
      parent.addChildAfter(child, previous);
      previous = child;
    }
    parent.removeChild(block);
    return true;
  } else {
    return false;
  }
}
 
Example 8
Source File: NodeUtil.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Merge a block with its parent block.
 * @return Whether the block was removed.
 */
static boolean tryMergeBlock(Node block) {
  Preconditions.checkState(block.isBlock());
  Node parent = block.getParent();
  // Try to remove the block if its parent is a block/script or if its
  // parent is label and it has exactly one child.
  if (isStatementBlock(parent)) {
    Node previous = block;
    while (block.hasChildren()) {
      Node child = block.removeFirstChild();
      parent.addChildAfter(child, previous);
      previous = child;
    }
    parent.removeChild(block);
    return true;
  } else {
    return false;
  }
}
 
Example 9
Source File: InstrumentFunctions.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (!n.isReturn()) {
    return;
  }

  Node call = newReportFunctionExitNode();
  Node returnRhs = n.removeFirstChild();
  if (returnRhs != null) {
    call.addChildToBack(returnRhs);
  }
  n.addChildToFront(call);
  compiler.reportCodeChange();
}
 
Example 10
Source File: Closure_20_PeepholeSubstituteAlternateSyntax_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to minimize NOT nodes such as !(x==y).
 *
 * Returns the replacement for n or the original if no change was made
 */
private Node tryMinimizeNot(Node n) {
  Node parent = n.getParent();

  Node notChild = n.getFirstChild();
  // negative operator of the current one : == -> != for instance.
  int complementOperator;
  switch (notChild.getType()) {
    case Token.EQ:
      complementOperator = Token.NE;
      break;
    case Token.NE:
      complementOperator = Token.EQ;
      break;
    case Token.SHEQ:
      complementOperator = Token.SHNE;
      break;
    case Token.SHNE:
      complementOperator = Token.SHEQ;
      break;
    // GT, GE, LT, LE are not handled in this because !(x<NaN) != x>=NaN.
    default:
      return n;
  }
  Node newOperator = n.removeFirstChild();
  newOperator.setType(complementOperator);
  parent.replaceChild(n, newOperator);
  reportCodeChange();
  return newOperator;
}
 
Example 11
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to minimize NOT nodes such as !(x==y).
 */
private boolean tryMinimizeNot(NodeTraversal t, Node n, Node parent) {
  Node notChild = n.getFirstChild();
  // negative operator of the current one : == -> != for instance.
  int complementOperator;
  switch (notChild.getType()) {
    case Token.EQ:
      complementOperator = Token.NE;
      break;
    case Token.NE:
      complementOperator = Token.EQ;
      break;
    case Token.SHEQ:
      complementOperator = Token.SHNE;
      break;
    case Token.SHNE:
      complementOperator = Token.SHEQ;
      break;
    // GT, GE, LT, LE are not handled in this because !(x<NaN) != x>=NaN.
    default:
      return false;
  }
  Node newOperator = n.removeFirstChild();
  newOperator.setType(complementOperator);
  parent.replaceChild(n, newOperator);
  t.getCompiler().reportCodeChange();
  return true;
}
 
Example 12
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 13
Source File: Closure_20_PeepholeSubstituteAlternateSyntax_t.java    From coming with MIT License 5 votes vote down vote up
private void tryJoinForCondition(Node n) {
  if (!late) {
    return;
  }

  Node block = n.getLastChild();
  Node maybeIf = block.getFirstChild();
  if (maybeIf != null && maybeIf.isIf()) {
    Node maybeBreak = maybeIf.getChildAtIndex(1).getFirstChild();
    if (maybeBreak != null && maybeBreak.isBreak()
        && !maybeBreak.hasChildren()) {

      // Preserve the IF ELSE expression is there is one.
      if (maybeIf.getChildCount() == 3) {
        block.replaceChild(maybeIf,
            maybeIf.getLastChild().detachFromParent());
      } else {
        block.removeFirstChild();
      }

      Node ifCondition = maybeIf.removeFirstChild();
      Node fixedIfCondition = IR.not(ifCondition)
          .srcref(ifCondition);

      // OK, join the IF expression with the FOR expression
      Node forCondition = NodeUtil.getConditionExpression(n);
      if (forCondition.isEmpty()) {
        n.replaceChild(forCondition, fixedIfCondition);
      } else {
        Node replacement = new Node(Token.AND);
        n.replaceChild(forCondition, replacement);
        replacement.addChildToBack(forCondition);
        replacement.addChildToBack(fixedIfCondition);
      }

      reportCodeChange();
    }
  }
}
 
Example 14
Source File: PeepholeSubstituteAlternateSyntax.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try to minimize NOT nodes such as !(x==y).
 *
 * Returns the replacement for n or the original if no change was made
 */
private Node tryMinimizeNot(Node n) {
  Node parent = n.getParent();

  Node notChild = n.getFirstChild();
  // negative operator of the current one : == -> != for instance.
  int complementOperator;
  switch (notChild.getType()) {
    case Token.EQ:
      complementOperator = Token.NE;
      break;
    case Token.NE:
      complementOperator = Token.EQ;
      break;
    case Token.SHEQ:
      complementOperator = Token.SHNE;
      break;
    case Token.SHNE:
      complementOperator = Token.SHEQ;
      break;
    // GT, GE, LT, LE are not handled in this because !(x<NaN) != x>=NaN.
    default:
      return n;
  }
  Node newOperator = n.removeFirstChild();
  newOperator.setType(complementOperator);
  parent.replaceChild(n, newOperator);
  reportCodeChange();
  return newOperator;
}
 
Example 15
Source File: PeepholeRemoveDeadCode.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes DOs that always evaluate to false. This leaves the
 * statements that were in the loop in a BLOCK node.
 * The block will be removed in a later pass, if possible.
 */
Node tryFoldDo(Node n) {
  Preconditions.checkArgument(n.isDo());

  Node cond = NodeUtil.getConditionExpression(n);
  if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) {
    return n;
  }

  // TODO(johnlenz): The do-while can be turned into a label with
  // named breaks and the label optimized away (maybe).
  if (hasBreakOrContinue(n)) {
    return n;
  }

  Preconditions.checkState(
      NodeUtil.isControlStructureCodeBlock(n, n.getFirstChild()));
  Node block = n.removeFirstChild();

  Node parent =  n.getParent();
  parent.replaceChild(n, block);
  if (mayHaveSideEffects(cond)) {
    Node condStatement = IR.exprResult(cond.detachFromParent())
        .srcref(cond);
    parent.addChildAfter(condStatement, block);
  }
  reportCodeChange();

  return n;
}
 
Example 16
Source File: Closure_20_PeepholeSubstituteAlternateSyntax_s.java    From coming with MIT License 5 votes vote down vote up
private void tryJoinForCondition(Node n) {
  if (!late) {
    return;
  }

  Node block = n.getLastChild();
  Node maybeIf = block.getFirstChild();
  if (maybeIf != null && maybeIf.isIf()) {
    Node maybeBreak = maybeIf.getChildAtIndex(1).getFirstChild();
    if (maybeBreak != null && maybeBreak.isBreak()
        && !maybeBreak.hasChildren()) {

      // Preserve the IF ELSE expression is there is one.
      if (maybeIf.getChildCount() == 3) {
        block.replaceChild(maybeIf,
            maybeIf.getLastChild().detachFromParent());
      } else {
        block.removeFirstChild();
      }

      Node ifCondition = maybeIf.removeFirstChild();
      Node fixedIfCondition = IR.not(ifCondition)
          .srcref(ifCondition);

      // OK, join the IF expression with the FOR expression
      Node forCondition = NodeUtil.getConditionExpression(n);
      if (forCondition.isEmpty()) {
        n.replaceChild(forCondition, fixedIfCondition);
      } else {
        Node replacement = new Node(Token.AND);
        n.replaceChild(forCondition, replacement);
        replacement.addChildToBack(forCondition);
        replacement.addChildToBack(fixedIfCondition);
      }

      reportCodeChange();
    }
  }
}
 
Example 17
Source File: Closure_132_PeepholeSubstituteAlternateSyntax_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to minimize NOT nodes such as !(x==y).
 *
 * Returns the replacement for n or the original if no change was made
 */
private Node tryMinimizeNot(Node n) {
  Node parent = n.getParent();

  Node notChild = n.getFirstChild();
  // negative operator of the current one : == -> != for instance.
  int complementOperator;
  switch (notChild.getType()) {
    case Token.EQ:
      complementOperator = Token.NE;
      break;
    case Token.NE:
      complementOperator = Token.EQ;
      break;
    case Token.SHEQ:
      complementOperator = Token.SHNE;
      break;
    case Token.SHNE:
      complementOperator = Token.SHEQ;
      break;
    // GT, GE, LT, LE are not handled in this because !(x<NaN) != x>=NaN.
    default:
      return n;
  }
  Node newOperator = n.removeFirstChild();
  newOperator.setType(complementOperator);
  parent.replaceChild(n, newOperator);
  reportCodeChange();
  return newOperator;
}
 
Example 18
Source File: 1_FunctionInjector.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Inline a function that fulfills the requirements of
 * canInlineReferenceDirectly into the call site, replacing only the CALL
 * node.
 */
private Node inlineReturnValue(Node callNode, Node fnNode) {
  Node block = fnNode.getLastChild();
  Node callParentNode = callNode.getParent();

  // NOTE: As the normalize pass guarantees globals aren't being
  // shadowed and an expression can't introduce new names, there is
  // no need to check for conflicts.

  // Create an argName -> expression map, checking for side effects.
  Map<String, Node> argMap =
      FunctionArgumentInjector.getFunctionCallParameterMap(
          fnNode, callNode, this.safeNameIdSupplier);

  Node newExpression;
  if (!block.hasChildren()) {
    Node srcLocation = block;
    newExpression = NodeUtil.newUndefinedNode(srcLocation);
  } else {
    Node returnNode = block.getFirstChild();
    Preconditions.checkArgument(returnNode.isReturn());

    // Clone the return node first.
    Node safeReturnNode = returnNode.cloneTree();
    Node inlineResult = FunctionArgumentInjector.inject(
        null, safeReturnNode, null, argMap);
    Preconditions.checkArgument(safeReturnNode == inlineResult);
    newExpression = safeReturnNode.removeFirstChild();
  }

  callParentNode.replaceChild(callNode, newExpression);
  return newExpression;
}
 
Example 19
Source File: ExpressionDecomposer.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rewrite the call so "this" is preserved.
 *   a.b(c);
 * becomes:
 *   var temp1 = a;
 *   var temp0 = temp1.b;
 *   temp0.call(temp1,c);
 *
 * @return The replacement node.
 */
private Node rewriteCallExpression(Node call, DecompositionState state) {
  Preconditions.checkArgument(call.isCall());
  Node first = call.getFirstChild();
  Preconditions.checkArgument(NodeUtil.isGet(first));

  // Extracts the expression representing the function to call. For example:
  //   "a['b'].c" from "a['b'].c()"
  Node getVarNode = extractExpression(
      first, state.extractBeforeStatement);
  state.extractBeforeStatement = getVarNode;

  // Extracts the object reference to be used as "this". For example:
  //   "a['b']" from "a['b'].c"
  Node getExprNode = getVarNode.getFirstChild().getFirstChild();
  Preconditions.checkArgument(NodeUtil.isGet(getExprNode));
  Node thisVarNode = extractExpression(
      getExprNode.getFirstChild(), state.extractBeforeStatement);
  state.extractBeforeStatement = thisVarNode;

  // Rewrite the CALL expression.
  Node thisNameNode = thisVarNode.getFirstChild();
  Node functionNameNode = getVarNode.getFirstChild();

  // CALL
  //   GETPROP
  //     functionName
  //     "call"
  //   thisName
  //   original-parameter1
  //   original-parameter2
  //   ...
  Node newCall = IR.call(
      IR.getprop(
          functionNameNode.cloneNode(),
          IR.string("call")),
      thisNameNode.cloneNode()).srcref(call);

  // Throw away the call name
  call.removeFirstChild();
  if (call.hasChildren()) {
    // Add the call parameters to the new call.
    newCall.addChildrenToBack(call.removeChildren());
  }

  // Replace the call.
  Node callParent = call.getParent();
  callParent.replaceChild(call, newCall);

  return newCall;
}
 
Example 20
Source File: Cardumen_0023_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Parse helper code needed by a reducer.
 *
 * @return Helper code root.  If parse fails, return null.
 */
public Node parseHelperCode(Reducer reducer) {
  Node root = compiler.parseSyntheticCode(
      reducer.getClass().toString() + ":helper", reducer.getHelperSource());
  return (root != null) ? root.removeFirstChild() : null;
}