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

The following examples show how to use com.google.javascript.rhino.Node#copyInformationFrom() . 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: SpecializeModule.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a definition of the original function that can be added as
 * a fixup in the modules that directly depend on the specialized module.
 *
 * <PRE>
 * The trick here is that even if the original function is declared as:
 *
 * function foo() {
 *   // stuff
 * }
 *
 * the fixup will have to be of the form
 *
 * foo = function() {
 *   // stuff
 * }
 * </PRE>
 *
 */
private Node generateFixupDefinition() {
  Node functionCopy = copiedOriginalFunction();

  Node nameNode;

  if (isAssignFunction) {
    nameNode =
       NodeUtil.newQualifiedNameNode(
           compiler.getCodingConvention(), name, functionCopy, name);
  } else {
    // Grab the name node from the original function and make that
    // function anonymous.
    nameNode = functionCopy.getFirstChild();
    functionCopy.replaceChild(nameNode,
        NodeUtil.newName(compiler.getCodingConvention(), "", nameNode));
  }

  Node assignment = IR.assign(nameNode, functionCopy);
  assignment.copyInformationFrom(functionCopy);

  return NodeUtil.newExpr(assignment);
}
 
Example 2
Source File: Closure_79_Normalize_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Limit the number of special cases where LABELs need to be handled. Only
 * BLOCK and loops are allowed to be labeled.  Loop labels must remain in
 * place as the named continues are not allowed for labeled blocks.
 */
private void normalizeLabels(Node n) {
  Preconditions.checkArgument(n.getType() == Token.LABEL);

  Node last = n.getLastChild();
  switch (last.getType()) {
    case Token.LABEL:
    case Token.BLOCK:
    case Token.FOR:
    case Token.WHILE:
    case Token.DO:
      return;
    default:
      Node block = new Node(Token.BLOCK);
      block.copyInformationFrom(last);
      n.replaceChild(last, block);
      block.addChildToFront(last);
      reportCodeChange("LABEL normalization");
      return;
  }
}
 
Example 3
Source File: Closure_79_Normalize_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Rewrite the function declaration from:
 *   function x() {}
 *   FUNCTION
 *     NAME
 *     LP
 *     BLOCK
 * to:
 *   var x = function() {};
 *   VAR
 *     NAME
 *       FUNCTION
 *         NAME (w/ empty string)
 *         LP
 *         BLOCK
 */
private void rewriteFunctionDeclaration(Node n) {
  // Prepare a spot for the function.
  Node oldNameNode = n.getFirstChild();
  Node fnNameNode = oldNameNode.cloneNode();
  Node var = new Node(Token.VAR, fnNameNode, n.getLineno(), n.getCharno());
  var.copyInformationFrom(n);

  // Prepare the function
  oldNameNode.setString("");

  // Move the function
  Node parent = n.getParent();
  parent.replaceChild(n, var);
  fnNameNode.addChildToFront(n);

  reportCodeChange("Function declaration");
}
 
Example 4
Source File: Closure_80_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a VAR node containing the given name and initial value expression.
 */
static Node newVarNode(String name, Node value) {
  Node nodeName = Node.newString(Token.NAME, name);
  if (value != null) {
    Preconditions.checkState(value.getNext() == null);
    nodeName.addChildToBack(value);
    nodeName.copyInformationFrom(value);
  }
  Node var = new Node(Token.VAR, nodeName)
      .copyInformationFrom(nodeName);

  return var;
}
 
Example 5
Source File: jKali_007_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace the current assign with its right hand side.
 */
void remove() {
  Node parent = assignNode.getParent();
  if (mayHaveSecondarySideEffects) {
    Node replacement = assignNode.getLastChild().detachFromParent();

    // Aggregate any expressions in GETELEMs.
    for (Node current = assignNode.getFirstChild();
         !current.isName();
         current = current.getFirstChild()) {
      if (current.isGetElem()) {
        replacement = IR.comma(
            current.getLastChild().detachFromParent(), replacement);
        replacement.copyInformationFrom(current);
      }
    }

    parent.replaceChild(assignNode, replacement);
  } else {
    Node gramps = parent.getParent();
    if (parent.isExprResult()) {
      gramps.removeChild(parent);
    } else {
      parent.replaceChild(assignNode,
          assignNode.getLastChild().detachFromParent());
    }
  }
}
 
Example 6
Source File: Closure_45_RemoveUnusedVars_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace the current assign with its right hand side.
 */
void remove() {
  Node parent = assignNode.getParent();
  if (mayHaveSecondarySideEffects) {
    Node replacement = assignNode.getLastChild().detachFromParent();

    // Aggregate any expressions in GETELEMs.
    for (Node current = assignNode.getFirstChild();
         !current.isName();
         current = current.getFirstChild()) {
      if (current.isGetElem()) {
        replacement = IR.comma(
            current.getLastChild().detachFromParent(), replacement);
        replacement.copyInformationFrom(current);
      }
    }

    parent.replaceChild(assignNode, replacement);
  } else {
    Node gramps = parent.getParent();
    if (parent.isExprResult()) {
      gramps.removeChild(parent);
    } else {
      parent.replaceChild(assignNode,
          assignNode.getLastChild().detachFromParent());
    }
  }
}
 
Example 7
Source File: Closure_132_PeepholeSubstituteAlternateSyntax_s.java    From coming with MIT License 5 votes vote down vote up
private Node trySplitComma(Node n) {
  if (late) {
    return n;
  }
  Node parent = n.getParent();
  Node left = n.getFirstChild();
  Node right = n.getLastChild();

  if (parent.isExprResult()
      && !parent.getParent().isLabel()) {
    // split comma
    n.detachChildren();
    // Replace the original expression with the left operand.
    parent.replaceChild(n, left);
    // Add the right expression afterward.
    Node newStatement = IR.exprResult(right);
    newStatement.copyInformationFrom(n);

    //This modifies outside the subtree, which is not
    //desirable in a peephole optimization.
    parent.getParent().addChildAfter(newStatement, parent);
    reportCodeChange();
    return left;
  } else {
    return n;
  }
}
 
Example 8
Source File: Closure_45_RemoveUnusedVars_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace the current assign with its right hand side.
 */
void remove() {
  Node parent = assignNode.getParent();
  if (mayHaveSecondarySideEffects) {
    Node replacement = assignNode.getLastChild().detachFromParent();

    // Aggregate any expressions in GETELEMs.
    for (Node current = assignNode.getFirstChild();
         !current.isName();
         current = current.getFirstChild()) {
      if (current.isGetElem()) {
        replacement = IR.comma(
            current.getLastChild().detachFromParent(), replacement);
        replacement.copyInformationFrom(current);
      }
    }

    parent.replaceChild(assignNode, replacement);
  } else {
    Node gramps = parent.getParent();
    if (parent.isExprResult()) {
      gramps.removeChild(parent);
    } else {
      parent.replaceChild(assignNode,
          assignNode.getLastChild().detachFromParent());
    }
  }
}
 
Example 9
Source File: Closure_86_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a VAR node containing the given name and initial value expression.
 */
static Node newVarNode(String name, Node value) {
  Node nodeName = Node.newString(Token.NAME, name);
  if (value != null) {
    Preconditions.checkState(value.getNext() == null);
    nodeName.addChildToBack(value);
    nodeName.copyInformationFrom(value);
  }
  Node var = new Node(Token.VAR, nodeName)
      .copyInformationFrom(nodeName);

  return var;
}
 
Example 10
Source File: Closure_60_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a VAR node containing the given name and initial value expression.
 */
static Node newVarNode(String name, Node value) {
  Node nodeName = Node.newString(Token.NAME, name);
  if (value != null) {
    Preconditions.checkState(value.getNext() == null);
    nodeName.addChildToBack(value);
    nodeName.copyInformationFrom(value);
  }
  Node var = new Node(Token.VAR, nodeName)
      .copyInformationFrom(nodeName);

  return var;
}
 
Example 11
Source File: Cardumen_00249_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace the current assign with its right hand side.
 */
void remove() {
  Node parent = assignNode.getParent();
  if (mayHaveSecondarySideEffects) {
    Node replacement = assignNode.getLastChild().detachFromParent();

    // Aggregate any expressions in GETELEMs.
    for (Node current = assignNode.getFirstChild();
         !current.isName();
         current = current.getFirstChild()) {
      if (current.isGetElem()) {
        replacement = IR.comma(
            current.getLastChild().detachFromParent(), replacement);
        replacement.copyInformationFrom(current);
      }
    }

    parent.replaceChild(assignNode, replacement);
  } else {
    Node gramps = parent.getParent();
    if (parent.isExprResult()) {
      gramps.removeChild(parent);
    } else {
      parent.replaceChild(assignNode,
          assignNode.getLastChild().detachFromParent());
    }
  }
}
 
Example 12
Source File: Closure_86_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a VAR node containing the given name and initial value expression.
 */
static Node newVarNode(String name, Node value) {
  Node nodeName = Node.newString(Token.NAME, name);
  if (value != null) {
    Preconditions.checkState(value.getNext() == null);
    nodeName.addChildToBack(value);
    nodeName.copyInformationFrom(value);
  }
  Node var = new Node(Token.VAR, nodeName)
      .copyInformationFrom(nodeName);

  return var;
}
 
Example 13
Source File: InlineObjectLiterals.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Splits up the object literal into individual variables, and
 * updates all uses.
 */
private void splitObject(Var v, Reference declaration,
                         Reference init,
                         ReferenceCollection referenceInfo) {
  // First figure out the FULL set of possible keys, so that they
  // can all be properly set as necessary.
  Map<String, String> varmap = computeVarList(v, referenceInfo);

  Map<String, Node> initvals = Maps.newHashMap();
  // Figure out the top-level of the var assign node. If it's a plain
  // ASSIGN, then there's an EXPR_STATEMENT above it, if it's a
  // VAR then it should be directly replaced.
  Node vnode;
  boolean defined = referenceInfo.isWellDefined() &&
      init.getParent().isVar();
  if (defined) {
    vnode = init.getParent();
    fillInitialValues(init, initvals);
  } else {
    // TODO(user): More test / rewrite this part.
    // Find the beginning of the function / script.
    vnode = v.getScope().getRootNode().getLastChild().getFirstChild();
  }

  for (Map.Entry<String, String> entry : varmap.entrySet()) {
    Node val = initvals.get(entry.getKey());
    Node varnode = NodeUtil.newVarNode(entry.getValue(), val);
    if (val == null) {
      // is this right?
      varnode.copyInformationFromForTree(vnode);
    } else {
      blacklistVarReferencesInTree(val, v.scope);
    }
    vnode.getParent().addChildBefore(varnode, vnode);
  }

  if (defined) {
    vnode.getParent().removeChild(vnode);
  }

  for (Reference ref : referenceInfo.references) {
    // The init/decl have already been converted.
    if (defined && ref == init) continue;

    if (ref.isLvalue()) {
      // Assignments have to be handled specially, since they
      // expand out into multiple assignments.
      replaceAssignmentExpression(v, ref, varmap);
    } else if (ref.getParent().isVar()) {
      // The old variable declaration. It didn't have a
      // value. Remove it entirely as it should now be unused.
      ref.getGrandparent().removeChild(ref.getParent());
    } else {
      // Make sure that the reference is a GETPROP as we expect it to be.
      Node getprop = ref.getParent();
      Preconditions.checkState(getprop.isGetProp());

      // The key being looked up in the original map.
      String var = getprop.getChildAtIndex(1).getString();

      // If the variable hasn't already been declared, add an empty
      // declaration near all the other declarations.
      Preconditions.checkState(varmap.containsKey(var));

      // Replace the GETPROP node with a NAME.
      Node replacement = IR.name(varmap.get(var));
      replacement.copyInformationFrom(getprop);
      ref.getGrandparent().replaceChild(ref.getParent(), replacement);
    }
  }

  compiler.reportCodeChange();
}
 
Example 14
Source File: Closure_53_InlineObjectLiterals_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Splits up the object literal into individual variables, and
 * updates all uses.
 */
private void splitObject(Var v, Reference declaration,
                         Reference init,
                         ReferenceCollection referenceInfo) {
  // First figure out the FULL set of possible keys, so that they
  // can all be properly set as necessary.
  Map<String, String> varmap = computeVarList(v, referenceInfo);

  Map<String, Node> initvals = Maps.newHashMap();
  // Figure out the top-level of the var assign node. If it's a plain
  // ASSIGN, then there's an EXPR_STATEMENT above it, if it's a
  // VAR then it should be directly replaced.
  Node vnode;
  boolean defined = referenceInfo.isWellDefined() &&
      init.getParent().getType() == Token.VAR;
  if (defined) {
    vnode = init.getParent();
    fillInitialValues(init, initvals);
  } else {
    // TODO(user): More test / rewrite this part.
    // Find the beginning of the function / script.
    vnode = v.getScope().getRootNode().getLastChild().getFirstChild();
  }

  for (Map.Entry<String, String> entry : varmap.entrySet()) {
    Node val = initvals.get(entry.getKey());
    Node varnode = NodeUtil.newVarNode(entry.getValue(), val);
    if (val == null) {
      // is this right?
      varnode.copyInformationFromForTree(vnode);
    } else {
      blacklistVarReferencesInTree(val, v.scope);
    }
    vnode.getParent().addChildBefore(varnode, vnode);
  }

  if (defined) {
    vnode.getParent().removeChild(vnode);
  }

  for (Reference ref : referenceInfo.references) {
    // The init/decl have already been converted.
    if (defined && ref == init) continue;

    if (ref.isLvalue()) {
      // Assignments have to be handled specially, since they
      // expand out into multiple assignments.
      replaceAssignmentExpression(v, ref, varmap);
    } else if (ref.getParent().getType() == Token.VAR) {
      // The old variable declaration. It didn't have a
      // value. Remove it entirely as it should now be unused.
      ref.getGrandparent().removeChild(ref.getParent());
    } else {
      // Make sure that the reference is a GETPROP as we expect it to be.
      Node getprop = ref.getParent();
      Preconditions.checkState(getprop.getType() == Token.GETPROP);

      // The key being looked up in the original map.
      String var = getprop.getChildAtIndex(1).getString();

      // If the variable hasn't already been declared, add an empty
      // declaration near all the other declarations.
      Preconditions.checkState(varmap.containsKey(var));

      // Replace the GETPROP node with a NAME.
      Node replacement = Node.newString(Token.NAME, varmap.get(var));
      replacement.copyInformationFrom(getprop);
      ref.getGrandparent().replaceChild(ref.getParent(), replacement);
    }
  }

  compiler.reportCodeChange();
}
 
Example 15
Source File: Closure_93_ProcessClosurePrimitives_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Replace the provide statement.
 *
 * If we're providing a name with no definition, then create one.
 * If we're providing a name with a duplicate definition, then make sure
 * that definition becomes a declaration.
 */
void replace() {
  if (firstNode == null) {
    // Don't touch the base case ('goog').
    replacementNode = candidateDefinition;
    return;
  }

  // Handle the case where there is a duplicate definition for an explicitly
  // provided symbol.
  if (candidateDefinition != null && explicitNode != null) {
    explicitNode.detachFromParent();
    compiler.reportCodeChange();

    // Does this need a VAR keyword?
    replacementNode = candidateDefinition;
    if (NodeUtil.isExpressionNode(candidateDefinition)) {
      candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true);
      Node assignNode = candidateDefinition.getFirstChild();
      Node nameNode = assignNode.getFirstChild();
      if (nameNode.getType() == Token.NAME) {
        // Need to convert this assign to a var declaration.
        Node valueNode = nameNode.getNext();
        assignNode.removeChild(nameNode);
        assignNode.removeChild(valueNode);
        nameNode.addChildToFront(valueNode);
        Node varNode = new Node(Token.VAR, nameNode);
        varNode.copyInformationFrom(candidateDefinition);
        candidateDefinition.getParent().replaceChild(
            candidateDefinition, varNode);
        nameNode.setJSDocInfo(assignNode.getJSDocInfo());
        compiler.reportCodeChange();
        replacementNode = varNode;
      }
    }
  } else {
    // Handle the case where there's not a duplicate definition.
    replacementNode = createDeclarationNode();
    if (firstModule == minimumModule) {
      firstNode.getParent().addChildBefore(replacementNode, firstNode);
    } else {
      // In this case, the name was implicitly provided by two independent
      // modules. We need to move this code up to a common module.
      int indexOfDot = namespace.indexOf('.');
      if (indexOfDot == -1) {
        // Any old place is fine.
        compiler.getNodeForCodeInsertion(minimumModule)
            .addChildToBack(replacementNode);
      } else {
        // Add it after the parent namespace.
        ProvidedName parentName =
            providedNames.get(namespace.substring(0, indexOfDot));
        Preconditions.checkNotNull(parentName);
        Preconditions.checkNotNull(parentName.replacementNode);
        parentName.replacementNode.getParent().addChildAfter(
            replacementNode, parentName.replacementNode);
      }
    }
    if (explicitNode != null) {
      explicitNode.detachFromParent();
    }
    compiler.reportCodeChange();
  }
}
 
Example 16
Source File: Closure_80_NodeUtil_s.java    From coming with MIT License 3 votes vote down vote up
/**
 * Creates a new node representing an *existing* name, copying over the source
 * location information from the basis node.
 *
 * @param name The name for the new NAME node.
 * @param basisNode The node that represents the name as currently found in
 *     the AST.
 *
 * @return The node created.
 */
static Node newName(
    CodingConvention convention, String name, Node basisNode) {
  Node nameNode = Node.newString(Token.NAME, name);
  if (convention.isConstantKey(name)) {
    nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
  }
  nameNode.copyInformationFrom(basisNode);
  return nameNode;
}
 
Example 17
Source File: Closure_60_NodeUtil_t.java    From coming with MIT License 3 votes vote down vote up
/**
 * Creates a new node representing an *existing* name, copying over the source
 * location information from the basis node.
 *
 * @param name The name for the new NAME node.
 * @param basisNode The node that represents the name as currently found in
 *     the AST.
 *
 * @return The node created.
 */
static Node newName(
    CodingConvention convention, String name, Node basisNode) {
  Node nameNode = Node.newString(Token.NAME, name);
  if (convention.isConstantKey(name)) {
    nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
  }
  nameNode.copyInformationFrom(basisNode);
  return nameNode;
}
 
Example 18
Source File: Closure_75_NodeUtil_t.java    From coming with MIT License 3 votes vote down vote up
/**
 * Creates a new node representing an *existing* name, copying over the source
 * location information from the basis node.
 *
 * @param name The name for the new NAME node.
 * @param basisNode The node that represents the name as currently found in
 *     the AST.
 *
 * @return The node created.
 */
static Node newName(
    CodingConvention convention, String name, Node basisNode) {
  Node nameNode = Node.newString(Token.NAME, name);
  if (convention.isConstantKey(name)) {
    nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
  }
  nameNode.copyInformationFrom(basisNode);
  return nameNode;
}
 
Example 19
Source File: Closure_86_NodeUtil_s.java    From coming with MIT License 3 votes vote down vote up
/**
 * Creates a new node representing an *existing* name, copying over the source
 * location information from the basis node.
 *
 * @param name The name for the new NAME node.
 * @param basisNode The node that represents the name as currently found in
 *     the AST.
 *
 * @return The node created.
 */
static Node newName(
    CodingConvention convention, String name, Node basisNode) {
  Node nameNode = Node.newString(Token.NAME, name);
  if (convention.isConstantKey(name)) {
    nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
  }
  nameNode.copyInformationFrom(basisNode);
  return nameNode;
}
 
Example 20
Source File: Closure_94_NodeUtil_s.java    From coming with MIT License 2 votes vote down vote up
/**
 * Creates a new node representing an *existing* name, copying over the source
 * location information from the basis node.
 *
 * @param name The name for the new NAME node.
 * @param basisNode The node that represents the name as currently found in
 *     the AST.
 *
 * @return The node created.
 */
static Node newName(String name, Node basisNode) {
  Node nameNode = Node.newString(Token.NAME, name);
  nameNode.copyInformationFrom(basisNode);
  return nameNode;
}