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

The following examples show how to use com.google.javascript.rhino.Node#newNumber() . 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_86_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a node for an empty result expression:
 *   "void 0"
 */
static Node newUndefinedNode(Node srcReferenceNode) {
  // TODO(johnlenz): Why this instead of the more common "undefined"?
  Node node = new Node(Token.VOID, Node.newNumber(0));
  if (srcReferenceNode != null) {
      node.copyInformationFromForTree(srcReferenceNode);
  }
  return node;
}
 
Example 2
Source File: Closure_74_PeepholeFoldConstants_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to fold array-length. e.g [1, 2, 3].length ==> 3, [x, y].length ==> 2
 */
private Node tryFoldGetProp(Node n, Node left, Node right) {
  Preconditions.checkArgument(n.getType() == Token.GETPROP);

  if (left.getType() == Token.OBJECTLIT) {
    return tryFoldObjectPropAccess(n, left, right);
  }

  if (right.getType() == Token.STRING &&
      right.getString().equals("length")) {
    int knownLength = -1;
    switch (left.getType()) {
      case Token.ARRAYLIT:
        if (mayHaveSideEffects(left)) {
          // Nope, can't fold this, without handling the side-effects.
          return n;
        }
        knownLength = left.getChildCount();
        break;
      case Token.STRING:
        knownLength = left.getString().length();
        break;
      default:
        // Not a foldable case, forget it.
        return n;
    }

    Preconditions.checkState(knownLength != -1);
    Node lengthNode = Node.newNumber(knownLength);
    n.getParent().replaceChild(n, lengthNode);
    reportCodeChange();

    return lengthNode;
  }

  return n;
}
 
Example 3
Source File: Closure_60_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a node for an empty result expression:
 *   "void 0"
 */
static Node newUndefinedNode(Node srcReferenceNode) {
  Node node = new Node(Token.VOID, Node.newNumber(0));
  if (srcReferenceNode != null) {
      node.copyInformationFromForTree(srcReferenceNode);
  }
  return node;
}
 
Example 4
Source File: Closure_80_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a node for an empty result expression:
 *   "void 0"
 */
static Node newUndefinedNode(Node srcReferenceNode) {
  Node node = new Node(Token.VOID, Node.newNumber(0));
  if (srcReferenceNode != null) {
      node.copyInformationFromForTree(srcReferenceNode);
  }
  return node;
}
 
Example 5
Source File: Closure_87_PeepholeSubstituteAlternateSyntax_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replaces a node with a number node if the new number node is not equivalent
 * to the current node.
 *
 * Returns the replacement for n if it was replaced, otherwise returns n.
 */
private Node maybeReplaceChildWithNumber(Node n, Node parent, int num) {
  Node newNode = Node.newNumber(num);
  if (!newNode.isEquivalentTo(n)) {
    parent.replaceChild(n, newNode);
    reportCodeChange();

    return newNode;
  }

  return n;
}
 
Example 6
Source File: Closure_50_PeepholeReplaceKnownMethods_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to fold .charCodeAt() calls on strings
 */
private Node tryFoldStringCharCodeAt(Node n, Node stringNode, Node arg1) {
  Preconditions.checkArgument(n.getType() == Token.CALL);
  Preconditions.checkArgument(stringNode.getType() == Token.STRING);

  int index;
  String stringAsString = stringNode.getString();

  if (arg1 != null && arg1.getType() == Token.NUMBER
      && arg1.getNext() == null) {
    index = (int) arg1.getDouble();
  } else {
    return n;
  }

  if (index < 0 || stringAsString.length() <= index) {
    // http://es5.github.com/#x15.5.4.5 says NaN is returned when index is
    // out of bounds but we bail.
    return n;
  }

  Node resultNode = Node.newNumber(stringAsString.charAt(index));
  Node parent = n.getParent();
  parent.replaceChild(n, resultNode);
  reportCodeChange();
  return resultNode;
}
 
Example 7
Source File: Closure_97_PeepholeFoldConstants_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to fold array-length. e.g [1, 2, 3].length ==> 3, [x, y].length ==> 2
 */
private Node tryFoldGetProp(Node n, Node left, Node right) {
  Preconditions.checkArgument(n.getType() == Token.GETPROP);

  if (right.getType() == Token.STRING &&
      right.getString().equals("length")) {
    int knownLength = -1;
    switch (left.getType()) {
      case Token.ARRAYLIT:
        if (NodeUtil.mayHaveSideEffects(left)) {
          // Nope, can't fold this, without handling the side-effects.
          return n;
        }
        knownLength = left.getChildCount();
        break;
      case Token.STRING:
        knownLength = left.getString().length();
        break;
      default:
        // Not a foldable case, forget it.
        return n;
    }

    Preconditions.checkState(knownLength != -1);
    Node lengthNode = Node.newNumber(knownLength);
    n.getParent().replaceChild(n, lengthNode);
    reportCodeChange();

    return lengthNode;
  }

  return n;
}
 
Example 8
Source File: Closure_75_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a node for an empty result expression:
 *   "void 0"
 */
static Node newUndefinedNode(Node srcReferenceNode) {
  Node node = new Node(Token.VOID, Node.newNumber(0));
  if (srcReferenceNode != null) {
      node.copyInformationFromForTree(srcReferenceNode);
  }
  return node;
}
 
Example 9
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to fold array-length. e.g [1, 2, 3].length ==> 3, [x, y].length ==> 2
 */
void tryFoldGetProp(NodeTraversal t, Node n, Node left, Node right,
                    Node parent) {
  if (right.getType() == Token.STRING &&
      right.getString().equals("length")) {
    int knownLength = -1;
    switch (left.getType()) {
      case Token.ARRAYLIT:
        if (NodeUtil.mayHaveSideEffects(left)) {
          // Nope, can't fold this, without handling the side-effects.
          return;
        }
        knownLength = left.getChildCount();
        break;
      case Token.STRING:
        knownLength = left.getString().length();
        break;
      default:
        // Not a foldable case, forget it.
        return;
    }

    Preconditions.checkState(knownLength != -1);
    Node lengthNode = Node.newNumber(knownLength);
    parent.replaceChild(n, lengthNode);
    t.getCompiler().reportCodeChange();
  }
}
 
Example 10
Source File: Closure_78_PeepholeFoldConstants_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Try to evaluate String.indexOf/lastIndexOf:
 *     "abcdef".indexOf("bc") -> 1
 *     "abcdefbc".indexOf("bc", 3) -> 6
 */
private Node tryFoldStringIndexOf(
    Node n, String functionName, Node lstringNode, Node firstArg) {
  Preconditions.checkArgument(n.getType() == Token.CALL);
  Preconditions.checkArgument(lstringNode.getType() == Token.STRING);

  String lstring = NodeUtil.getStringValue(lstringNode);
  boolean isIndexOf = functionName.equals("indexOf");
  Node secondArg = firstArg.getNext();
  String searchValue = NodeUtil.getStringValue(firstArg);
  // searchValue must be a valid string.
  if (searchValue == null) {
    return n;
  }
  int fromIndex = isIndexOf ? 0 : lstring.length();
  if (secondArg != null) {
    // Third-argument and non-numeric second arg are problematic. Discard.
    if ((secondArg.getNext() != null) ||
        (secondArg.getType() != Token.NUMBER)) {
      return n;
    } else {
      fromIndex = (int) secondArg.getDouble();
    }
  }
  int indexVal = isIndexOf ? lstring.indexOf(searchValue, fromIndex)
                           : lstring.lastIndexOf(searchValue, fromIndex);
  Node newNode = Node.newNumber(indexVal);
  n.getParent().replaceChild(n, newNode);

  reportCodeChange();

  return newNode;
}
 
Example 11
Source File: Closure_87_PeepholeSubstituteAlternateSyntax_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replaces a node with a number node if the new number node is not equivalent
 * to the current node.
 *
 * Returns the replacement for n if it was replaced, otherwise returns n.
 */
private Node maybeReplaceChildWithNumber(Node n, Node parent, int num) {
  Node newNode = Node.newNumber(num);
  if (!newNode.isEquivalentTo(n)) {
    parent.replaceChild(n, newNode);
    reportCodeChange();

    return newNode;
  }

  return n;
}
 
Example 12
Source File: Closure_94_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a node for an empty result expression:
 *   "void 0"
 */
static Node newUndefinedNode(Node srcReferenceNode) {
  // TODO(johnlenz): Why this instead of the more common "undefined"?
  Node node = new Node(Token.VOID, Node.newNumber(0));
  if (srcReferenceNode != null) {
      node.copyInformationFromForTree(srcReferenceNode);
  }
  return node;
}
 
Example 13
Source File: Closure_94_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a node for an empty result expression:
 *   "void 0"
 */
static Node newUndefinedNode(Node srcReferenceNode) {
  // TODO(johnlenz): Why this instead of the more common "undefined"?
  Node node = new Node(Token.VOID, Node.newNumber(0));
  if (srcReferenceNode != null) {
      node.copyInformationFromForTree(srcReferenceNode);
  }
  return node;
}
 
Example 14
Source File: Closure_74_PeepholeFoldConstants_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold shift operations
 */
private Node tryFoldShift(Node n, Node left, Node right) {
  if (left.getType() == Token.NUMBER &&
      right.getType() == Token.NUMBER) {

    double result;
    double lval = left.getDouble();
    double rval = right.getDouble();

    // check ranges.  We do not do anything that would clip the double to
    // a 32-bit range, since the user likely does not intend that.
    if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) {
      error(BITWISE_OPERAND_OUT_OF_RANGE, left);
      return n;
    }

    // only the lower 5 bits are used when shifting, so don't do anything
    // if the shift amount is outside [0,32)
    if (!(rval >= 0 && rval < 32)) {
      error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right);
      return n;
    }

    // Convert the numbers to ints
    int lvalInt = (int) lval;
    if (lvalInt != lval) {
      error(FRACTIONAL_BITWISE_OPERAND, left);
      return n;
    }

    int rvalInt = (int) rval;
    if (rvalInt != rval) {
      error(FRACTIONAL_BITWISE_OPERAND, right);
      return n;
    }

    switch (n.getType()) {
      case Token.LSH:
        result = lvalInt << rvalInt;
        break;
      case Token.RSH:
        result = lvalInt >> rvalInt;
        break;
      case Token.URSH:
        // JavaScript handles zero shifts on signed numbers differently than
        // Java as an Java int can not represent the unsigned 32-bit number
        // where JavaScript can so use a long here.
        long lvalLong = lvalInt & 0xffffffffL;
        result = lvalLong >>> rvalInt;
        break;
      default:
        throw new AssertionError("Unknown shift operator: " +
            Node.tokenToName(n.getType()));
    }

    Node newNumber = Node.newNumber(result);
    n.getParent().replaceChild(n, newNumber);
    reportCodeChange();

    return newNumber;
  }

  return n;
}
 
Example 15
Source File: Closure_97_PeepholeFoldConstants_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold arithmetic binary operators
 */
private Node tryFoldBitAndOr(Node n, Node left, Node right) {
  Preconditions.checkArgument(n.getType() == Token.BITAND
      || n.getType() == Token.BITOR);

  if (left.getType() == Token.NUMBER &&
      right.getType() == Token.NUMBER) {
    double resultDouble;
    double lval = left.getDouble();
    double rval = right.getDouble();

    // For now, we are being extra conservative, and only folding ints in
    // the range MIN_VALUE-MAX_VALUE
    if (lval < Integer.MIN_VALUE || lval > Integer.MAX_VALUE ||
        rval < Integer.MIN_VALUE || rval > Integer.MAX_VALUE) {

      // Fall back through and let the javascript use the larger values
      return n;
    }

    // Convert the numbers to ints
    int lvalInt = (int) lval;
    if (lvalInt != lval) {
      return n;
    }

    int rvalInt = (int) rval;
    if (rvalInt != rval) {
      return n;
    }

    switch (n.getType()) {
      case Token.BITAND:
        resultDouble = lvalInt & rvalInt;
        break;
      case Token.BITOR:
        resultDouble = lvalInt | rvalInt;
        break;
      default:
        throw new Error("Unknown bitwise operator");
    }

    Node newNumber = Node.newNumber(resultDouble);
    n.getParent().replaceChild(n, newNumber);
    reportCodeChange();
  }

  return n;
}
 
Example 16
Source File: SemanticReverseAbstractInterpreterTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private Node createUntypedNumber(int n) {
  return Node.newNumber(n);
}
 
Example 17
Source File: Closure_97_PeepholeFoldConstants_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to evaluate String.indexOf/lastIndexOf:
 *     "abcdef".indexOf("bc") -> 1
 *     "abcdefbc".indexOf("bc", 3) -> 6
 */
private Node tryFoldStringIndexOf(Node n) {
  Preconditions.checkArgument(n.getType() == Token.CALL);

  Node left = n.getFirstChild();

  if (left == null) {
    return n;
  }

  Node right = left.getNext();

  if (right == null) {
    return n;
  }

  if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) {
    return n;
  }

  Node lstringNode = left.getFirstChild();
  Node functionName = lstringNode.getNext();

  if ((lstringNode.getType() != Token.STRING) ||
      (!functionName.getString().equals("indexOf") &&
      !functionName.getString().equals("lastIndexOf"))) {
    return n;
  }

  String lstring = NodeUtil.getStringValue(lstringNode);
  boolean isIndexOf = functionName.getString().equals("indexOf");
  Node firstArg = right;
  Node secondArg = right.getNext();
  String searchValue = NodeUtil.getStringValue(firstArg);
  // searchValue must be a valid string.
  if (searchValue == null) {
    return n;
  }
  int fromIndex = isIndexOf ? 0 : lstring.length();
  if (secondArg != null) {
    // Third-argument and non-numeric second arg are problematic. Discard.
    if ((secondArg.getNext() != null) ||
        (secondArg.getType() != Token.NUMBER)) {
      return n;
    } else {
      fromIndex = (int) secondArg.getDouble();
    }
  }
  int indexVal = isIndexOf ? lstring.indexOf(searchValue, fromIndex)
                           : lstring.lastIndexOf(searchValue, fromIndex);
  Node newNode = Node.newNumber(indexVal);
  n.getParent().replaceChild(n, newNode);

  reportCodeChange();

  return newNode;
}
 
Example 18
Source File: Closure_97_PeepholeFoldConstants_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold shift operations
 */
private Node tryFoldShift(Node n, Node left, Node right) {
  if (left.getType() == Token.NUMBER &&
      right.getType() == Token.NUMBER) {

    double result;
    double lval = left.getDouble();
    double rval = right.getDouble();

    // check ranges.  We do not do anything that would clip the double to
    // a 32-bit range, since the user likely does not intend that.
    if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) {
      error(BITWISE_OPERAND_OUT_OF_RANGE, left);
      return n;
    }

    // only the lower 5 bits are used when shifting, so don't do anything
    // if the shift amount is outside [0,32)
    if (!(rval >= 0 && rval < 32)) {
      error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right);
      return n;
    }

    // Convert the numbers to ints
    int lvalInt = (int) lval;
    if (lvalInt != lval) {
      error(FRACTIONAL_BITWISE_OPERAND, left);
      return n;
    }

    int rvalInt = (int) rval;
    if (rvalInt != rval) {
      error(FRACTIONAL_BITWISE_OPERAND, right);
      return n;
    }

    switch (n.getType()) {
      case Token.LSH:
        result = lvalInt << rvalInt;
        break;
      case Token.RSH:
        result = lvalInt >> rvalInt;
        break;
      case Token.URSH:
        // JavaScript handles zero shifts on signed numbers differently than
        // Java as an Java int can not represent the unsigned 32-bit number
        // where JavaScript can so use a long here.
        long lvalLong = lvalInt & 0xffffffffL;
        result = lvalLong >>> rvalInt;
        break;
      default:
        throw new AssertionError("Unknown shift operator: " +
            Node.tokenToName(n.getType()));
    }

    Node newNumber = Node.newNumber(result);
    n.getParent().replaceChild(n, newNumber);
    reportCodeChange();

    return newNumber;
  }

  return n;
}
 
Example 19
Source File: Closure_97_PeepholeFoldConstants_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to evaluate String.indexOf/lastIndexOf:
 *     "abcdef".indexOf("bc") -> 1
 *     "abcdefbc".indexOf("bc", 3) -> 6
 */
private Node tryFoldStringIndexOf(Node n) {
  Preconditions.checkArgument(n.getType() == Token.CALL);

  Node left = n.getFirstChild();

  if (left == null) {
    return n;
  }

  Node right = left.getNext();

  if (right == null) {
    return n;
  }

  if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) {
    return n;
  }

  Node lstringNode = left.getFirstChild();
  Node functionName = lstringNode.getNext();

  if ((lstringNode.getType() != Token.STRING) ||
      (!functionName.getString().equals("indexOf") &&
      !functionName.getString().equals("lastIndexOf"))) {
    return n;
  }

  String lstring = NodeUtil.getStringValue(lstringNode);
  boolean isIndexOf = functionName.getString().equals("indexOf");
  Node firstArg = right;
  Node secondArg = right.getNext();
  String searchValue = NodeUtil.getStringValue(firstArg);
  // searchValue must be a valid string.
  if (searchValue == null) {
    return n;
  }
  int fromIndex = isIndexOf ? 0 : lstring.length();
  if (secondArg != null) {
    // Third-argument and non-numeric second arg are problematic. Discard.
    if ((secondArg.getNext() != null) ||
        (secondArg.getType() != Token.NUMBER)) {
      return n;
    } else {
      fromIndex = (int) secondArg.getDouble();
    }
  }
  int indexVal = isIndexOf ? lstring.indexOf(searchValue, fromIndex)
                           : lstring.lastIndexOf(searchValue, fromIndex);
  Node newNode = Node.newNumber(indexVal);
  n.getParent().replaceChild(n, newNode);

  reportCodeChange();

  return newNode;
}
 
Example 20
Source File: Closure_78_PeepholeFoldConstants_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold arithmetic binary operators
 */
private Node performArithmeticOp(int opType, Node left, Node right) {
  // Unlike other operations, ADD operands are not always converted
  // to Number.
  if (opType == Token.ADD
      && (NodeUtil.mayBeString(left, false)
          || NodeUtil.mayBeString(right, false))) {
    return null;
  }

  double result;

  // TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN
  // to zero so this is a little akward here.

  Double lValObj = NodeUtil.getNumberValue(left);
  if (lValObj == null) {
    return null;
  }
  Double rValObj = NodeUtil.getNumberValue(right);
  if (rValObj == null) {
    return null;
  }

  double lval = lValObj;
  double rval = rValObj;

  switch (opType) {
    case Token.BITAND:
      result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval);
      break;
    case Token.BITOR:
      result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval);
      break;
    case Token.BITXOR:
      result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval);
      break;
    case Token.ADD:
      result = lval + rval;
      break;
    case Token.SUB:
      result = lval - rval;
      break;
    case Token.MUL:
      result = lval * rval;
      break;
    case Token.MOD:
      if (rval == 0) {
        return null;
      }
      result = lval % rval;
      break;
    case Token.DIV:
      if (rval == 0) {
        return null;
      }
      result = lval / rval;
      break;
    default:
      throw new Error("Unexpected arithmetic operator");
  }

  // TODO(johnlenz): consider removing the result length check.
  // length of the left and right value plus 1 byte for the operator.
  if (String.valueOf(result).length() <=
      String.valueOf(lval).length() + String.valueOf(rval).length() + 1 &&

      // Do not try to fold arithmetic for numbers > 2^53. After that
      // point, fixed-point math starts to break down and become inaccurate.
      Math.abs(result) <= MAX_FOLD_NUMBER) {
    Node newNumber = Node.newNumber(result);
    return newNumber;
  } else if (Double.isNaN(result)) {
    return Node.newString(Token.NAME, "NaN");
  } else if (result == Double.POSITIVE_INFINITY) {
    return Node.newString(Token.NAME, "Infinity");
  } else if (result == Double.NEGATIVE_INFINITY) {
    return new Node(Token.NEG, Node.newString(Token.NAME, "Infinity"));
  }

  return null;
}