Java Code Examples for com.google.javascript.rhino.IR#string()

The following examples show how to use com.google.javascript.rhino.IR#string() . 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: jMutRepair_003_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example 2
Source File: Closure_10_NodeUtil_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example 3
Source File: Closure_23_PeepholeFoldConstants_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Try to fold an ADD node with constant operands
 */
private Node tryFoldAddConstantString(Node n, Node left, Node right) {
  if (left.isString() ||
      right.isString()) {
    // Add strings.
    String leftString = NodeUtil.getStringValue(left);
    String rightString = NodeUtil.getStringValue(right);
    if (leftString != null && rightString != null) {
      Node newStringNode = IR.string(leftString + rightString);
      n.getParent().replaceChild(n, newStringNode);
      reportCodeChange();
      return newStringNode;
    }
  }



  return n;
}
 
Example 4
Source File: AliasExternals.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds a string that can be used to reference properties by array []
 * notation.
 *
 * PROP_prototype = 'prototype';
 *
 * @param propName Name of property
 * @param root Root of output tree that function can be added to
 */
private void addAccessorPropName(String propName, Node root) {
  /*
   *  Target:

    var 1
      name PROP_length
          string length
   */
  Node propValue = IR.string(propName);
  Node propNameNode =
      IR.name(getArrayNotationNameFor(propName));
  propNameNode.addChildToFront(propValue);
  Node var = IR.var(propNameNode);
  root.addChildToFront(var);

  compiler.reportCodeChange();
}
 
Example 5
Source File: Cardumen_00200_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example 6
Source File: jKali_003_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example 7
Source File: jKali_003_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example 8
Source File: Cardumen_0087_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example 9
Source File: Cardumen_0014_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example 10
Source File: PeepholeReplaceKnownMethods.java    From astor with GNU General Public License v2.0 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 = IR.string(lowered);
  subtree.getParent().replaceChild(subtree, replacement);
  reportCodeChange();
  return replacement;
}
 
Example 11
Source File: PeepholeReplaceKnownMethods.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try to fold .charAt() calls on strings
 */
private Node tryFoldStringCharAt(Node n, Node stringNode, Node arg1) {
  Preconditions.checkArgument(n.isCall());
  Preconditions.checkArgument(stringNode.isString());

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

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

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

  Node resultNode = IR.string(
      stringAsString.substring(index, index + 1));
  Node parent = n.getParent();
  parent.replaceChild(n, resultNode);
  reportCodeChange();
  return resultNode;
}
 
Example 12
Source File: RuntimeTypeCheck.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private Node addMarker(
        FunctionType funType,
        Node nodeToInsertAfter,
        @Nullable ObjectType interfaceType) {

  if (funType.getSource() == null) {
    return nodeToInsertAfter;
  }

  String className = NodeUtil.getFunctionName(funType.getSource());

  // This can happen with anonymous classes declared with the type
  // {@code Function}.
  if (className == null) {
    return nodeToInsertAfter;
  }

  Node classNode = NodeUtil.newQualifiedNameNode(
      compiler.getCodingConvention(), className);

  Node marker = IR.string(
          interfaceType == null ?
          "instance_of__" + className :
          "implements__" + interfaceType.getReferenceName());

  Node assign = IR.exprResult(IR.assign(
      IR.getelem(
          IR.getprop(
              classNode,
              IR.string("prototype")), marker),
      IR.trueNode()));

  nodeToInsertAfter.getParent().addChildAfter(assign, nodeToInsertAfter);
  compiler.reportCodeChange();
  nodeToInsertAfter = assign;
  return nodeToInsertAfter;
}
 
Example 13
Source File: Closure_23_PeepholeFoldConstants_s.java    From coming with MIT License 5 votes vote down vote up
private Node tryFoldInForcedStringContext(Node n) {
  // For now, we only know how to fold ctors.
  Preconditions.checkArgument(n.isNew());

  Node objectType = n.getFirstChild();
  if (!objectType.isName()) {
    return n;
  }

  if (objectType.getString().equals("String")) {
    Node value = objectType.getNext();
    String stringValue = null;
    if (value == null) {
      stringValue = "";
    } else {
      if (!NodeUtil.isImmutableValue(value)) {
        return n;
      }

      stringValue = NodeUtil.getStringValue(value);
    }

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

    Node parent = n.getParent();
    Node newString = IR.string(stringValue);

    parent.replaceChild(n, newString);
    newString.copyInformationFrom(parent);
    reportCodeChange();

    return newString;
  }
  return n;
}
 
Example 14
Source File: ProcessTweaks.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
Node createDefaultValueNode() {
  switch (this) {
    case REGISTER_BOOLEAN:
      return IR.falseNode();
    case REGISTER_NUMBER:
      return IR.number(0);
    case REGISTER_STRING:
      return IR.string("");
    default:
      throw new IllegalStateException();
  }
}
 
Example 15
Source File: ReplaceMessages.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a parse tree corresponding to the remaining message parts in
 * an iteration. The result will contain only STRING nodes, NAME nodes
 * (corresponding to placeholder references), and/or ADD nodes used to
 * combine the other two types.
 *
 * @param partsIterator  an iterator over message parts
 * @param argListNode  an LP node whose children are valid placeholder names
 * @return the root of the constructed parse tree
 *
 * @throws MalformedException if {@code partsIterator} contains a
 *   placeholder reference that does not correspond to a valid argument in
 *   the arg list
 */
private Node constructAddOrStringNode(Iterator<CharSequence> partsIterator,
                                      Node argListNode)
    throws MalformedException {
  CharSequence part = partsIterator.next();
  Node partNode = null;
  if (part instanceof JsMessage.PlaceholderReference) {
    JsMessage.PlaceholderReference phRef =
        (JsMessage.PlaceholderReference) part;

    for (Node node : argListNode.children()) {
      if (node.isName()) {
        String arg = node.getString();

        // We ignore the case here because the transconsole only supports
        // uppercase placeholder names, but function arguments in JavaScript
        // code can have mixed case.
        if (arg.equalsIgnoreCase(phRef.getName())) {
          partNode = IR.name(arg);
        }
      }
    }

    if (partNode == null) {
      throw new MalformedException(
          "Unrecognized message placeholder referenced: " + phRef.getName(),
          argListNode);
    }
  } else {
    // The part is just a string literal.
    partNode = IR.string(part.toString());
  }

  if (partsIterator.hasNext()) {
    return IR.add(partNode,
                    constructAddOrStringNode(partsIterator, argListNode));
  } else {
    return partNode;
  }
}
 
Example 16
Source File: Closure_23_PeepholeFoldConstants_t.java    From coming with MIT License 5 votes vote down vote up
private Node tryFoldInForcedStringContext(Node n) {
  // For now, we only know how to fold ctors.
  Preconditions.checkArgument(n.isNew());

  Node objectType = n.getFirstChild();
  if (!objectType.isName()) {
    return n;
  }

  if (objectType.getString().equals("String")) {
    Node value = objectType.getNext();
    String stringValue = null;
    if (value == null) {
      stringValue = "";
    } else {
      if (!NodeUtil.isImmutableValue(value)) {
        return n;
      }

      stringValue = NodeUtil.getStringValue(value);
    }

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

    Node parent = n.getParent();
    Node newString = IR.string(stringValue);

    parent.replaceChild(n, newString);
    newString.copyInformationFrom(parent);
    reportCodeChange();

    return newString;
  }
  return n;
}
 
Example 17
Source File: ReplaceMessages.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a node representing a message's value, or, if possible, just
 * modifies {@code origValueNode} so that it accurately represents the
 * message's value.
 *
 * @param message  a message
 * @param origValueNode  the message's original value node
 * @return a Node that can replace {@code origValueNode}
 *
 * @throws MalformedException if the passed node's subtree structure is
 *   not as expected
 */
private Node getNewValueNode(JsMessage message, Node origValueNode)
    throws MalformedException {
  switch (origValueNode.getType()) {
    case Token.FUNCTION:
      // The message is a function. Modify the function node.
      updateFunctionNode(message, origValueNode);
      return origValueNode;
    case Token.STRING:
      // The message is a simple string. Modify the string node.
      String newString = message.toString();
      if (!origValueNode.getString().equals(newString)) {
        origValueNode.setString(newString);
        compiler.reportCodeChange();
      }
      return origValueNode;
    case Token.ADD:
      // The message is a simple string. Create a string node.
      return IR.string(message.toString());
    case Token.CALL:
      // The message is a function call. Replace it with a string expression.
      return replaceCallNode(message, origValueNode);
    default:
      throw new MalformedException(
          "Expected FUNCTION, STRING, or ADD node; found: " +
              origValueNode.getType(), origValueNode);
  }
}
 
Example 18
Source File: PeepholeFoldConstants.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Folds 'typeof(foo)' if foo is a literal, e.g.
 * typeof("bar") --> "string"
 * typeof(6) --> "number"
 */
private Node tryFoldTypeof(Node originalTypeofNode) {
  Preconditions.checkArgument(originalTypeofNode.isTypeOf());

  Node argumentNode = originalTypeofNode.getFirstChild();
  if (argumentNode == null || !NodeUtil.isLiteralValue(argumentNode, true)) {
    return originalTypeofNode;
  }

  String typeNameString = null;

  switch (argumentNode.getType()) {
    case Token.FUNCTION:
      typeNameString = "function";
      break;
    case Token.STRING:
      typeNameString = "string";
      break;
    case Token.NUMBER:
      typeNameString = "number";
      break;
    case Token.TRUE:
    case Token.FALSE:
      typeNameString = "boolean";
      break;
    case Token.NULL:
    case Token.OBJECTLIT:
    case Token.ARRAYLIT:
      typeNameString = "object";
      break;
    case Token.VOID:
      typeNameString = "undefined";
      break;
    case Token.NAME:
      // We assume here that programs don't change the value of the
      // keyword undefined to something other than the value undefined.
      if ("undefined".equals(argumentNode.getString())) {
        typeNameString = "undefined";
      }
      break;
  }

  if (typeNameString != null) {
    Node newNode = IR.string(typeNameString);
    originalTypeofNode.getParent().replaceChild(originalTypeofNode, newNode);
    reportCodeChange();

    return newNode;
  }

  return originalTypeofNode;
}
 
Example 19
Source File: Closure_23_PeepholeFoldConstants_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Folds 'typeof(foo)' if foo is a literal, e.g.
 * typeof("bar") --> "string"
 * typeof(6) --> "number"
 */
private Node tryFoldTypeof(Node originalTypeofNode) {
  Preconditions.checkArgument(originalTypeofNode.isTypeOf());

  Node argumentNode = originalTypeofNode.getFirstChild();
  if (argumentNode == null || !NodeUtil.isLiteralValue(argumentNode, true)) {
    return originalTypeofNode;
  }

  String typeNameString = null;

  switch (argumentNode.getType()) {
    case Token.FUNCTION:
      typeNameString = "function";
      break;
    case Token.STRING:
      typeNameString = "string";
      break;
    case Token.NUMBER:
      typeNameString = "number";
      break;
    case Token.TRUE:
    case Token.FALSE:
      typeNameString = "boolean";
      break;
    case Token.NULL:
    case Token.OBJECTLIT:
    case Token.ARRAYLIT:
      typeNameString = "object";
      break;
    case Token.VOID:
      typeNameString = "undefined";
      break;
    case Token.NAME:
      // We assume here that programs don't change the value of the
      // keyword undefined to something other than the value undefined.
      if ("undefined".equals(argumentNode.getString())) {
        typeNameString = "undefined";
      }
      break;
  }

  if (typeNameString != null) {
    Node newNode = IR.string(typeNameString);
    originalTypeofNode.getParent().replaceChild(originalTypeofNode, newNode);
    reportCodeChange();

    return newNode;
  }

  return originalTypeofNode;
}
 
Example 20
Source File: ReplaceMessages.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Updates the descendants of a FUNCTION node to represent a message's value.
 * <p>
 * The tree looks something like:
 * <pre>
 * function
 *  |-- name
 *  |-- lp
 *  |   |-- name <arg1>
 *  |    -- name <arg2>
 *   -- block
 *      |
 *       --return
 *           |
 *            --add
 *               |-- string foo
 *                -- name <arg1>
 * </pre>
 *
 * @param message  a message
 * @param functionNode  the message's original FUNCTION value node
 *
 * @throws MalformedException if the passed node's subtree structure is
 *         not as expected
 */
private void updateFunctionNode(JsMessage message, Node functionNode)
    throws MalformedException {
  checkNode(functionNode, Token.FUNCTION);
  Node nameNode = functionNode.getFirstChild();
  checkNode(nameNode, Token.NAME);
  Node argListNode = nameNode.getNext();
  checkNode(argListNode, Token.PARAM_LIST);
  Node oldBlockNode = argListNode.getNext();
  checkNode(oldBlockNode, Token.BLOCK);

  Iterator<CharSequence> iterator = message.parts().iterator();
  Node valueNode = iterator.hasNext()
      ? constructAddOrStringNode(iterator, argListNode)
      : IR.string("");
  Node newBlockNode = IR.block(IR.returnNode(valueNode));

  // TODO(user): checkTreeEqual is overkill. I am in process of rewriting
  // these functions.
  if (newBlockNode.checkTreeEquals(oldBlockNode) != null) {
    newBlockNode.copyInformationFromForTree(oldBlockNode);
    functionNode.replaceChild(oldBlockNode, newBlockNode);
    compiler.reportCodeChange();
  }
}