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

The following examples show how to use com.google.javascript.rhino.Node#newString() . 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: ConcreteTypeTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Creates a fake function with the given description. */
private ConcreteFunctionType createFunction(
    String name, String... paramNames) {
  Node args = new Node(Token.PARAM_LIST);
  for (int i = 0; i < paramNames.length; ++i) {
    args.addChildToBack(Node.newString(Token.NAME, paramNames[i]));
  }

  Node decl = new Node(Token.FUNCTION,
                       Node.newString(Token.NAME, name),
                       args,
                       new Node(Token.BLOCK));

  JSType[] paramTypes = new JSType[paramNames.length];
  Arrays.fill(paramTypes, unknownType);
  decl.setJSType(typeRegistry.createConstructorType(
      name, decl, args, unknownType, null));

  return new ConcreteFunctionType(factory, decl, null);
}
 
Example 2
Source File: Closure_93_ProcessClosurePrimitives_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a simple namespace variable declaration
 * (e.g. <code>var foo = {};</code>).
 *
 * @param namespace A simple namespace (must be a valid js identifier)
 * @param sourceNode The node to get source information from.
 */
private Node makeVarDeclNode(String namespace, Node sourceNode) {
  Node name = Node.newString(Token.NAME, namespace);
  name.addChildToFront(createNamespaceLiteral());

  Node decl = new Node(Token.VAR, name);
  decl.putBooleanProp(Node.IS_NAMESPACE, true);

  // TODO(nicksantos): ew ew ew. Create a mutator package.
  if (compiler.getCodingConvention().isConstant(namespace)) {
    name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
  }

  Preconditions.checkState(isNamespacePlaceholder(decl));
  decl.copyInformationFromForTree(sourceNode);
  return decl;
}
 
Example 3
Source File: Closure_60_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 4
Source File: Closure_75_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 5
Source File: Closure_86_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
private static Node newName(
    CodingConvention convention, String name, int lineno, int charno) {
  Node nameNode = Node.newString(Token.NAME, name, lineno, charno);
  if (convention.isConstant(name)) {
    nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
  }
  return nameNode;
}
 
Example 6
Source File: Closure_72_FunctionToBlockMutator_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace the 'return' statement with its child expression.
 *   "return foo()" becomes "{foo(); break;}" or
 *      "{resultName = foo(); break;}"
 *   "return" becomes {break;} or "{resultName = void 0;break;}".
 */
private static Node replaceReturnWithBreak(Node current, Node parent,
    String resultName, String labelName) {

  if (current.getType() == Token.FUNCTION
      || current.getType() == Token.EXPR_RESULT) {
    // Don't recurse into functions definitions, and expressions can't
    // contain RETURN nodes.
    return current;
  }

  if (current.getType() == Token.RETURN) {
    Preconditions.checkState(NodeUtil.isStatementBlock(parent));

    Node resultNode = getReplacementReturnStatement(current, resultName);
    Node name = Node.newString(Token.LABEL_NAME, labelName);
    Node breakNode = new Node(Token.BREAK, name);

    // Replace the node in parent, and reset current to the first new child.
    breakNode.copyInformationFromForTree(current);
    parent.replaceChild(current, breakNode);
    if (resultNode != null) {
      resultNode.copyInformationFromForTree(current);
      parent.addChildBefore(resultNode, breakNode);
    }
    current = breakNode;
  } else {
    for (Node c = current.getFirstChild(); c != null; c = c.getNext()) {
      // c may be replaced.
      c = replaceReturnWithBreak(c, current, resultName, labelName);
    }
  }

  return current;
}
 
Example 7
Source File: GatherSideEffectSubexpressionsCallbackTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testIllegalArgumentIfNotHook() throws Exception {
  Node nameNode = Node.newString(Token.NAME, "foo");
  try {
    checkKeepSimplifiedHookExpr(nameNode,
                                true,
                                true,
                                ImmutableList.<String>of());
    fail("Expected exception");
  } catch (IllegalArgumentException e) {
    // ignore
  }
}
 
Example 8
Source File: TypeConversionPass.java    From clutz with MIT License 5 votes vote down vote up
private Node createMemberVariableDef(ClassMemberDeclaration declaration) {
  Node fieldNode = Node.newString(Token.MEMBER_VARIABLE_DEF, declaration.memberName);
  fieldNode.setJSDocInfo(declaration.jsDoc);
  fieldNode.setStaticMember(declaration.isStatic);
  nodeComments.moveComment(declaration.exprRoot, fieldNode);
  return fieldNode;
}
 
Example 9
Source File: Closure_78_PeepholeFoldConstants_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return The uppered string Node.
 */
private Node tryFoldStringToUpperCase(Node subtree, Node stringNode) {
  // From Rhino, NativeString.java. See ECMA 15.5.4.12
  String uppered = stringNode.getString().toUpperCase(ROOT_LOCALE);
  Node replacement = Node.newString(uppered);
  subtree.getParent().replaceChild(subtree, replacement);
  reportCodeChange();
  return replacement;
}
 
Example 10
Source File: Closure_78_PeepholeFoldConstants_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return The lowered string Node.
 */
private Node tryFoldStringToLowerCase(Node subtree, Node stringNode) {
  // From Rhino, NativeString.java. See ECMA 15.5.4.11
  String lowered = stringNode.getString().toLowerCase(ROOT_LOCALE);
  Node replacement = Node.newString(lowered);
  subtree.getParent().replaceChild(subtree, replacement);
  reportCodeChange();
  return replacement;
}
 
Example 11
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 12
Source File: Closure_94_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 13
Source File: Closure_74_PeepholeFoldConstants_s.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;
}
 
Example 14
Source File: Closure_78_PeepholeFoldConstants_s.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) {
        error(DiagnosticType.error("JSC_DIVIDE_BY_0_ERROR", "Divide by 0"), right);
        return null;
      }
      result = lval % rval;
      break;
    case Token.DIV:
      if (rval == 0) {
        error(DiagnosticType.error("JSC_DIVIDE_BY_0_ERROR", "Divide by 0"), right);
        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;
}
 
Example 15
Source File: Closure_78_PeepholeFoldConstants_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold .substr() calls on strings
 */
private Node tryFoldStringSubstr(Node n, Node stringNode, Node arg1) {
  Preconditions.checkArgument(n.getType() == Token.CALL);
  Preconditions.checkArgument(stringNode.getType() == Token.STRING);

  int start, length;
  String stringAsString = stringNode.getString();

  // TODO(nicksantos): We really need a NodeUtil.getNumberValue
  // function.
  if (arg1 != null && arg1.getType() == Token.NUMBER) {
    start = (int) arg1.getDouble();
  } else {
    return n;
  }

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

    if (arg2.getNext() != null) {
      // If we got more args than we expected, bail out.
      return n;
    }
  } else {
    // parameter 2 not passed
    length = stringAsString.length() - start;
  }

  // Don't handle these cases. The specification actually does
  // specify the behavior in some of these cases, but we haven't
  // done a thorough investigation that it is correctly implemented
  // in all browsers.
  if ((start + length) > stringAsString.length() ||
      (length < 0) ||
      (start < 0)) {
    return n;
  }

  String result = stringAsString.substring(start, start + length);
  Node resultNode = Node.newString(result);

  Node parent = n.getParent();
  parent.replaceChild(n, resultNode);
  reportCodeChange();
  return resultNode;
}
 
Example 16
Source File: Closure_50_PeepholeReplaceKnownMethods_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold .substring() calls on strings
 */
private Node tryFoldStringSubstring(Node n, Node stringNode, Node arg1) {
  Preconditions.checkArgument(n.getType() == Token.CALL);
  Preconditions.checkArgument(stringNode.getType() == Token.STRING);

  int start, end;
  String stringAsString = stringNode.getString();

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

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

    if (arg2.getNext() != null) {
      // If we got more args than we expected, bail out.
      return n;
    }
  } else {
    // parameter 2 not passed
    end = stringAsString.length();
  }

  // Don't handle these cases. The specification actually does
  // specify the behavior in some of these cases, but we haven't
  // done a thorough investigation that it is correctly implemented
  // in all browsers.
  if ((end > stringAsString.length()) ||
      (start > stringAsString.length()) ||
      (end < 0) ||
      (start < 0)) {
    return n;
  }

  String result = stringAsString.substring(start, end);
  Node resultNode = Node.newString(result);

  Node parent = n.getParent();
  parent.replaceChild(n, resultNode);
  reportCodeChange();
  return resultNode;
}
 
Example 17
Source File: Closure_74_PeepholeFoldConstants_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold .substring() calls on strings
 */
private Node tryFoldStringSubstring(Node n, Node stringNode, Node arg1) {
  Preconditions.checkArgument(n.getType() == Token.CALL);
  Preconditions.checkArgument(stringNode.getType() == Token.STRING);

  int start, end;
  String stringAsString = stringNode.getString();

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

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

    if (arg2.getNext() != null) {
      // If we got more args than we expected, bail out.
      return n;
    }
  } else {
    // parameter 2 not passed
    end = stringAsString.length();
  }

  // Don't handle these cases. The specification actually does
  // specify the behavior in some of these cases, but we haven't
  // done a thorough investigation that it is correctly implemented
  // in all browsers.
  if ((end > stringAsString.length()) ||
      (start > stringAsString.length()) ||
      (end < 0) ||
      (start < 0)) {
    return n;
  }

  String result = stringAsString.substring(start, end);
  Node resultNode = Node.newString(result);

  Node parent = n.getParent();
  parent.replaceChild(n, resultNode);
  reportCodeChange();
  return resultNode;
}
 
Example 18
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 19
Source File: Closure_74_PeepholeFoldConstants_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold .substr() calls on strings
 */
private Node tryFoldStringSubstr(Node n, Node stringNode, Node arg1) {
  Preconditions.checkArgument(n.getType() == Token.CALL);
  Preconditions.checkArgument(stringNode.getType() == Token.STRING);

  int start, length;
  String stringAsString = stringNode.getString();

  // TODO(nicksantos): We really need a NodeUtil.getNumberValue
  // function.
  if (arg1 != null && arg1.getType() == Token.NUMBER) {
    start = (int) arg1.getDouble();
  } else {
    return n;
  }

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

    if (arg2.getNext() != null) {
      // If we got more args than we expected, bail out.
      return n;
    }
  } else {
    // parameter 2 not passed
    length = stringAsString.length() - start;
  }

  // Don't handle these cases. The specification actually does
  // specify the behavior in some of these cases, but we haven't
  // done a thorough investigation that it is correctly implemented
  // in all browsers.
  if ((start + length) > stringAsString.length() ||
      (length < 0) ||
      (start < 0)) {
    return n;
  }

  String result = stringAsString.substring(start, start + length);
  Node resultNode = Node.newString(result);

  Node parent = n.getParent();
  parent.replaceChild(n, resultNode);
  reportCodeChange();
  return resultNode;
}
 
Example 20
Source File: Closure_60_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;
}