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

The following examples show how to use com.google.javascript.rhino.Node#isBlock() . 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: AbstractPeepholeOptimization.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if the specified node is null or is still in the AST.
 */
@VisibleForTesting
static Node validateResult(Node n) {
  done: {
    if (n != null && !n.isScript()
        && (!n.isBlock() || !n.isSyntheticBlock())) {
      for (Node parent : n.getAncestors()) {
        if (parent.isScript()) {
          break done;
        }
      }
      Preconditions.checkState(false);
    }
  }
  return n;
}
 
Example 2
Source File: Closure_14_ControlFlowAnalysis_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Locate the catch BLOCK given the first block in a TRY.
 * @return The CATCH node or null there is no catch handler.
 */
static Node getCatchHandlerForBlock(Node block) {
  if (block.isBlock() &&
      block.getParent().isTry() &&
      block.getParent().getFirstChild() == block) {
    for (Node s = block.getNext(); s != null; s = s.getNext()) {
      if (NodeUtil.hasCatchHandler(s)) {
        return s.getFirstChild();
      }
    }
  }
  return null;
}
 
Example 3
Source File: Closure_20_PeepholeSubstituteAlternateSyntax_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return Whether the node is a block with a single statement that is
 *     an return with or without an expression.
 */
private boolean isReturnBlock(Node n) {
  if (n.isBlock()) {
    if (n.hasOneChild()) {
      Node first = n.getFirstChild();
      return first.isReturn();
    }
  }

  return false;
}
 
Example 4
Source File: Cardumen_0014_t.java    From coming with MIT License 5 votes vote down vote up
@Override
public boolean apply(Node n) {
  Node parent = n.getParent();
  return n.isBlock()
      || (!n.isFunction() && (parent == null
          || isControlStructure(parent)
          || isStatementBlock(parent)));
}
 
Example 5
Source File: jMutRepair_003_t.java    From coming with MIT License 5 votes vote down vote up
@Override
public boolean apply(Node n) {
  Node parent = n.getParent();
  return n.isBlock()
      || (!n.isFunction() && (parent == null
          || isControlStructure(parent)
          || isStatementBlock(parent)));
}
 
Example 6
Source File: Cardumen_0014_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns whether this a BLOCK node with no children.
 *
 * @param block The node.
 */
static boolean isEmptyBlock(Node block) {
  if (!block.isBlock()) {
    return false;
  }

  for (Node n = block.getFirstChild(); n != null; n = n.getNext()) {
    if (!n.isEmpty()) {
      return false;
    }
  }
  return true;
}
 
Example 7
Source File: Closure_14_ControlFlowAnalysis_t.java    From coming with MIT License 5 votes vote down vote up
private void handleStmtList(Node node) {
  Node parent = node.getParent();
  // Special case, don't add a block of empty CATCH block to the graph.
  if (node.isBlock() && parent != null &&
      parent.isTry() &&
      NodeUtil.getCatchBlock(parent) == node &&
      !NodeUtil.hasCatchHandler(node)) {
    return;
  }

  // A block transfer control to its first child if it is not empty.
  Node child = node.getFirstChild();

  // Function declarations are skipped since control doesn't go into that
  // function (unless it is called)
  while (child != null && child.isFunction()) {
    child = child.getNext();
  }

  if (child != null) {
    createEdge(node, Branch.UNCOND, computeFallThrough(child));
  } else {
    createEdge(node, Branch.UNCOND, computeFollowNode(node, this));
  }

  // Synthetic blocks
  if (parent != null) {
    switch (parent.getType()) {
      case Token.DEFAULT_CASE:
      case Token.CASE:
      case Token.TRY:
        break;
      default:
        if (node.isBlock() && node.isSyntheticBlock()) {
          createEdge(node, Branch.SYN_BLOCK, computeFollowNode(node, this));
        }
        break;
    }
  }
}
 
Example 8
Source File: Closure_34_CodeGenerator_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param maxCount The maximum number of children to look for.
 * @return The number of children of this node that are non empty up to
 * maxCount.
 */
private static int getNonEmptyChildCount(Node n, int maxCount) {
  int i = 0;
  Node c = n.getFirstChild();
  for (; c != null && i < maxCount; c = c.getNext()) {
    if (c.isBlock()) {
      i += getNonEmptyChildCount(c, maxCount-i);
    } else if (!c.isEmpty()) {
      i++;
    }
  }
  return i;
}
 
Example 9
Source File: RenameLabels.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Rename or remove labels.
 * @param node  The label node.
 * @param parent The parent of the label node.
 */
private void visitLabel(Node node, Node parent) {
  Node nameNode = node.getFirstChild();
  Preconditions.checkState(nameNode != null);
  String name = nameNode.getString();
  LabelInfo li = getLabelInfo(name);
  // This is a label...
  if (li.referenced || !removeUnused) {
    String newName = getNameForId(li.id);
    if (!name.equals(newName)) {
      // ... and it is used, give it the short name.
      nameNode.setString(newName);
      compiler.reportCodeChange();
    }
  } else {
    // ... and it is not referenced, just remove it.
    Node newChild = node.getLastChild();
    node.removeChild(newChild);
    parent.replaceChild(node, newChild);
    if (newChild.isBlock()) {
      NodeUtil.tryMergeBlock(newChild);
    }
    compiler.reportCodeChange();
  }

  // Remove the label from the current stack of labels.
  namespaceStack.peek().renameMap.remove(name);
}
 
Example 10
Source File: Cardumen_00200_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns whether this a BLOCK node with no children.
 *
 * @param block The node.
 */
static boolean isEmptyBlock(Node block) {
  if (!block.isBlock()) {
    return false;
  }

  for (Node n = block.getFirstChild(); n != null; n = n.getNext()) {
    if (!n.isEmpty()) {
      return false;
    }
  }
  return true;
}
 
Example 11
Source File: StatementFusion.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private boolean canFuseIntoOneStatement(Node block) {
  // Fold only statement block. NOT scripts block.
  if (!block.isBlock()) {
    return false;
  }

  // Nothing to do here.
  if (!block.hasChildren() || block.hasOneChild()) {
    return false;
  }

  Node last = block.getLastChild();

  for (Node c = block.getFirstChild(); c != null; c = c.getNext()) {
    if (!c.isExprResult() && c != last) {
      return false;
    }
  }

  // TODO(user): Support more control statement for fusion.
  // FOR
  switch(last.getType()) {
    case Token.IF:
    case Token.THROW:
    case Token.SWITCH:
    case Token.EXPR_RESULT:
      return true;
    case Token.RETURN:
      // We don't want to add a new return value.
      return last.hasChildren();
    case Token.FOR:
      return NodeUtil.isForIn(last) &&
          // Avoid cases where we have for(var x = foo() in a) { ....
          !mayHaveSideEffects(last.getFirstChild());
  }

  return false;
}
 
Example 12
Source File: ControlFlowAnalysis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void handleStmtList(Node node) {
  Node parent = node.getParent();
  // Special case, don't add a block of empty CATCH block to the graph.
  if (node.isBlock() && parent != null &&
      parent.isTry() &&
      NodeUtil.getCatchBlock(parent) == node &&
      !NodeUtil.hasCatchHandler(node)) {
    return;
  }

  // A block transfer control to its first child if it is not empty.
  Node child = node.getFirstChild();

  // Function declarations are skipped since control doesn't go into that
  // function (unless it is called)
  while (child != null && child.isFunction()) {
    child = child.getNext();
  }

  if (child != null) {
    createEdge(node, Branch.UNCOND, computeFallThrough(child));
  } else {
    createEdge(node, Branch.UNCOND, computeFollowNode(node, this));
  }

  // Synthetic blocks
  if (parent != null) {
    switch (parent.getType()) {
      case Token.DEFAULT_CASE:
      case Token.CASE:
      case Token.TRY:
        break;
      default:
        if (node.isBlock() && node.isSyntheticBlock()) {
          createEdge(node, Branch.SYN_BLOCK, computeFollowNode(node, this));
        }
        break;
    }
  }
}
 
Example 13
Source File: Closure_128_CodeGenerator_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param maxCount The maximum number of children to look for.
 * @return The number of children of this node that are non empty up to
 * maxCount.
 */
private static int getNonEmptyChildCount(Node n, int maxCount) {
  int i = 0;
  Node c = n.getFirstChild();
  for (; c != null && i < maxCount; c = c.getNext()) {
    if (c.isBlock()) {
      i += getNonEmptyChildCount(c, maxCount-i);
    } else if (!c.isEmpty()) {
      i++;
    }
  }
  return i;
}
 
Example 14
Source File: Cardumen_0087_t.java    From coming with MIT License 5 votes vote down vote up
@Override
public boolean apply(Node n) {
  Node parent = n.getParent();
  return n.isBlock()
      || (!n.isFunction() && (parent == null
          || isControlStructure(parent)
          || isStatementBlock(parent)));
}
 
Example 15
Source File: 1_ControlFlowAnalysis.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Locate the catch BLOCK given the first block in a TRY.
 * @return The CATCH node or null there is no catch handler.
 */
static Node getCatchHandlerForBlock(Node block) {
  if (block.isBlock() &&
      block.getParent().isTry() &&
      block.getParent().getFirstChild() == block) {
    for (Node s = block.getNext(); s != null; s = s.getNext()) {
      if (NodeUtil.hasCatchHandler(s)) {
        return s.getFirstChild();
      }
    }
  }
  return null;
}
 
Example 16
Source File: Closure_123_CodeGenerator_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Adds a block or expression, substituting a VOID with an empty statement.
 * This is used for "for (...);" and "if (...);" type statements.
 *
 * @param n The node to print.
 * @param context The context to determine how the node should be printed.
 */
private void addNonEmptyStatement(
    Node n, Context context, boolean allowNonBlockChild) {
  Node nodeToProcess = n;

  if (!allowNonBlockChild && !n.isBlock()) {
    throw new Error("Missing BLOCK child.");
  }

  // Strip unneeded blocks, that is blocks with <2 children unless
  // the CodePrinter specifically wants to keep them.
  if (n.isBlock()) {
    int count = getNonEmptyChildCount(n, 2);
    if (count == 0) {
      if (cc.shouldPreserveExtraBlocks()) {
        cc.beginBlock();
        cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
      } else {
        cc.endStatement(true);
      }
      return;
    }

    if (count == 1) {
      // Hack around a couple of browser bugs:
      //   Safari needs a block around function declarations.
      //   IE6/7 needs a block around DOs.
      Node firstAndOnlyChild = getFirstNonEmptyChild(n);
      boolean alwaysWrapInBlock = cc.shouldPreserveExtraBlocks();
      if (alwaysWrapInBlock || isOneExactlyFunctionOrDo(firstAndOnlyChild)) {
        cc.beginBlock();
        add(firstAndOnlyChild, Context.STATEMENT);
        cc.maybeLineBreak();
        cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
        return;
      } else {
        // Continue with the only child.
        nodeToProcess = firstAndOnlyChild;
      }
    }

    if (count > 1) {
      context = Context.PRESERVE_BLOCK;
    }
  }

  if (nodeToProcess.isEmpty()) {
    cc.endStatement(true);
  } else {
    add(nodeToProcess, context);

    // VAR doesn't include ';' since it gets used in expressions - so any
    // VAR in a statement context needs a call to endStatement() here.
    if (nodeToProcess.isVar()) {
      cc.endStatement();
    }
  }
}
 
Example 17
Source File: Closure_130_CollapseProperties_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Updates the initial assignment to a collapsible property at global scope
 * by changing it to a variable declaration (e.g. a.b = 1 -> var a$b = 1).
 * The property's value may either be a primitive or an object literal or
 * function whose properties aren't collapsible.
 *
 * @param alias The flattened property name (e.g. "a$b")
 * @param refName The name for the reference being updated.
 * @param ref An object containing information about the assignment getting
 *     updated
 */
private void updateSimpleDeclaration(String alias, Name refName, Ref ref) {
  Node rvalue = ref.node.getNext();
  Node parent = ref.node.getParent();
  Node gramps = parent.getParent();
  Node greatGramps = gramps.getParent();

  if (rvalue != null && rvalue.isFunction()) {
    checkForHosedThisReferences(rvalue, refName.docInfo, refName);
  }

  // Create the new alias node.
  Node nameNode = NodeUtil.newName(
      compiler.getCodingConvention(), alias, gramps.getFirstChild(),
      refName.getFullName());
  NodeUtil.copyNameAnnotations(ref.node.getLastChild(), nameNode);

  if (gramps.isExprResult()) {
    // BEFORE: a.b.c = ...;
    //   exprstmt
    //     assign
    //       getprop
    //         getprop
    //           name a
    //           string b
    //         string c
    //       NODE
    // AFTER: var a$b$c = ...;
    //   var
    //     name a$b$c
    //       NODE

    // Remove the r-value (NODE).
    parent.removeChild(rvalue);
    nameNode.addChildToFront(rvalue);

    Node varNode = IR.var(nameNode);
    greatGramps.replaceChild(gramps, varNode);
  } else {
    // This must be a complex assignment.
    Preconditions.checkNotNull(ref.getTwin());

    // BEFORE:
    // ... (x.y = 3);
    //
    // AFTER:
    // var x$y;
    // ... (x$y = 3);

    Node current = gramps;
    Node currentParent = gramps.getParent();
    for (; !currentParent.isScript() &&
           !currentParent.isBlock();
         current = currentParent,
         currentParent = currentParent.getParent()) {}

    // Create a stub variable declaration right
    // before the current statement.
    Node stubVar = IR.var(nameNode.cloneTree())
        .copyInformationFrom(nameNode);
    currentParent.addChildBefore(stubVar, current);

    parent.replaceChild(ref.node, nameNode);
  }

  compiler.reportCodeChange();
}
 
Example 18
Source File: Cardumen_00200_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node is of a type that contain other statements.
 */
static boolean isStatementBlock(Node n) {
  return n.isScript() || n.isBlock();
}
 
Example 19
Source File: Cardumen_00149_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node is of a type that contain other statements.
 */
static boolean isStatementBlock(Node n) {
  return n.isScript() || n.isBlock();
}
 
Example 20
Source File: Closure_126_MinimizeExitPoints_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Look for exits (returns, breaks, or continues, depending on the context) at
 * the end of a block and removes them by moving the if node's siblings,
 * if any, into the opposite condition block.
 *
 * @param srcBlock The block to inspect.
 * @param destBlock The block to move sibling nodes into.
 * @param ifNode The if node to work with.
 * @param exitType The type of exit to look for.
 * @param labelName The name associated with the exit, if any.
 * @nullable labelName null for anything excepted for named-break associated
 *           with a label.
 */
private void tryMinimizeIfBlockExits(Node srcBlock, Node destBlock,
    Node ifNode, int exitType, String labelName) {
  Node exitNodeParent = null;
  Node exitNode = null;

  // Pick an exit node candidate.
  if (srcBlock.isBlock()) {
    if (!srcBlock.hasChildren()) {
      return;
    }
    exitNodeParent = srcBlock;
    exitNode = exitNodeParent.getLastChild();
  } else {
    // Just a single statement, if it isn't an exit bail.
    exitNodeParent = ifNode;
    exitNode = srcBlock;
  }

  // Verify the candidate.
  if (!matchingExitNode(exitNode, exitType, labelName)) {
    return;
  }

  // Take case of the if nodes siblings, if any.
  if (ifNode.getNext() != null) {
    // Move siblings of the if block into the opposite
    // logic block of the exit.
    Node newDestBlock = IR.block().srcref(ifNode);
    if (destBlock == null) {
      // Only possible if this is the false block.
      ifNode.addChildToBack(newDestBlock);
    } else if (destBlock.isEmpty()) {
      // Use the new block.
      ifNode.replaceChild(destBlock, newDestBlock);
    } else if (destBlock.isBlock()) {
      // Reuse the existing block.
      newDestBlock = destBlock;
    } else {
      // Add the existing statement to the new block.
      ifNode.replaceChild(destBlock, newDestBlock);
      newDestBlock.addChildToBack(destBlock);
    }

    // Move all the if node's following siblings.
    moveAllFollowing(ifNode, ifNode.getParent(), newDestBlock);
    compiler.reportCodeChange();
  }
}