Java Code Examples for com.google.javascript.rhino.Token#ARRAYLIT

The following examples show how to use com.google.javascript.rhino.Token#ARRAYLIT . 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: 1_ClosureCodingConvention.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<String> identifyTypeDeclarationCall(Node n) {
  Node callName = n.getFirstChild();
  if ("goog.addDependency".equals(callName.getQualifiedName()) &&
      n.getChildCount() >= 3) {
    Node typeArray = callName.getNext().getNext();
    if (typeArray.getType() == Token.ARRAYLIT) {
      List<String> typeNames = Lists.newArrayList();
      for (Node name = typeArray.getFirstChild(); name != null;
           name = name.getNext()) {
        if (name.getType() == Token.STRING) {
          typeNames.add(name.getString());
        }
      }
      return typeNames;
    }
  }
  return null;
}
 
Example 2
Source File: Closure_86_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns true if this is a literal value. We define a literal value
 * as any node that evaluates to the same thing regardless of when or
 * where it is evaluated. So /xyz/ and [3, 5] are literals, but
 * the name a is not.
 *
 * Function literals do not meet this definition, because they
 * lexically capture variables. For example, if you have
 * <code>
 * function() { return a; }
 * </code>
 * If it is evaluated in a different scope, then it
 * captures a different variable. Even if the function did not read
 * any captured vairables directly, it would still fail this definition,
 * because it affects the lifecycle of variables in the enclosing scope.
 *
 * However, a function literal with respect to a particular scope is
 * a literal.
 *
 * @param includeFunctions If true, all function expressions will be
 *     treated as literals.
 */
static boolean isLiteralValue(Node n, boolean includeFunctions) {
  switch (n.getType()) {
    case Token.ARRAYLIT:
    case Token.REGEXP:
      // Return true only if all children are const.
      for (Node child = n.getFirstChild(); child != null;
           child = child.getNext()) {
        if (!isLiteralValue(child, includeFunctions)) {
          return false;
        }
      }
      return true;

    case Token.OBJECTLIT:
      // Return true only if all values are const.
      for (Node child = n.getFirstChild(); child != null;
           child = child.getNext()) {
        if (!isLiteralValue(child.getFirstChild(), includeFunctions)) {
          return false;
        }
      }
      return true;

    case Token.FUNCTION:
      return includeFunctions && !NodeUtil.isFunctionDeclaration(n);

    default:
      return isImmutableValue(n);
  }
}
 
Example 3
Source File: Closure_80_NodeUtil_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Is this an ARRAYLIT node
 */
static boolean isArrayLiteral(Node node) {
  return node.getType() == Token.ARRAYLIT;
}
 
Example 4
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold array-element. e.g [1, 2, 3][10];
 */
void tryFoldGetElem(NodeTraversal t, Node n, Node left, Node right,
                    Node parent) {
  if (left.getType() == Token.ARRAYLIT) {

    if (right.getType() != Token.NUMBER) {
      // Sometimes people like to use complex expressions to index into
      // arrays, or strings to index into array methods.
      return;
    }

    double index = right.getDouble();
    int intIndex = (int) index;
    if (intIndex != index) {
      t.getCompiler().report(JSError.make(t, right,
          INVALID_GETELEM_INDEX_ERROR, String.valueOf(index)));
      return;
    }

    if (intIndex < 0) {
      t.getCompiler().report(JSError.make(t, n, INDEX_OUT_OF_BOUNDS_ERROR,
          String.valueOf(intIndex)));
      return;
    }

    Node elem = left.getFirstChild();
    for (int i = 0; elem != null && i < intIndex; i++) {
      elem = elem.getNext();
    }

    if (elem == null) {
      t.getCompiler().report(JSError.make(t, n, INDEX_OUT_OF_BOUNDS_ERROR,
          String.valueOf(intIndex)));
      return;
    }

    // Replace the entire GETELEM with the value
    left.removeChild(elem);
    parent.replaceChild(n, elem);
    t.getCompiler().reportCodeChange();
  }
}
 
Example 5
Source File: jKali_003_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the value of a node as a String, or null if it cannot be converted.
 * When it returns a non-null String, this method effectively emulates the
 * <code>String()</code> JavaScript cast function.
 */
static String getStringValue(Node n) {
  // TODO(user): regex literals as well.
  switch (n.getType()) {
    case Token.STRING:
    case Token.STRING_KEY:
      return n.getString();

    case Token.NAME:
      String name = n.getString();
      if ("undefined".equals(name)
          || "Infinity".equals(name)
          || "NaN".equals(name)) {
        return name;
      }
      break;

    case Token.NUMBER:
      return getStringValue(n.getDouble());

    case Token.FALSE:
      return "false";

    case Token.TRUE:
      return "true";

    case Token.NULL:
      return "null";

    case Token.VOID:
      return "undefined";

    case Token.NOT:
      TernaryValue child = getPureBooleanValue(n.getFirstChild());
      if (child != TernaryValue.UNKNOWN) {
        return child.toBoolean(true) ? "false" : "true"; // reversed.
      }
      break;

    case Token.ARRAYLIT:
      return arrayToString(n);

    case Token.OBJECTLIT:
      return "[object Object]";
  }
  return null;
}
 
Example 6
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to fold an array join: ['a', 'b', 'c'].join('') -> 'abc';
 */
void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right,
                       Node parent) {
  if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) {
    return;
  }

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

  if ((arrayNode.getType() != Token.ARRAYLIT) ||
      !functionName.getString().equals("join")) {
    return;
  }

  String joinString = NodeUtil.getStringValue(right);
  List<Node> arrayFoldedChildren = Lists.newLinkedList();
  StringBuilder sb = new StringBuilder();
  int foldedSize = 0;
  Node elem = arrayNode.getFirstChild();
  // Merges adjacent String nodes.
  while (elem != null) {
    if (NodeUtil.isImmutableValue(elem)) {
      if (sb.length() > 0) {
        sb.append(joinString);
      }
      sb.append(NodeUtil.getStringValue(elem));
    } else {
      if (sb.length() > 0) {
        // + 2 for the quotes.
        foldedSize += sb.length() + 2;
        arrayFoldedChildren.add(Node.newString(sb.toString()));
        sb = new StringBuilder();
      }
      foldedSize += InlineCostEstimator.getCost(elem);
      arrayFoldedChildren.add(elem);
    }
    elem = elem.getNext();
  }

  if (sb.length() > 0) {
    // + 2 for the quotes.
    foldedSize += sb.length() + 2;
    arrayFoldedChildren.add(Node.newString(sb.toString()));
  }
  // one for each comma.
  foldedSize += arrayFoldedChildren.size() - 1;

  int originalSize = InlineCostEstimator.getCost(n);
  switch (arrayFoldedChildren.size()) {
    case 0:
      Node emptyStringNode = Node.newString("");
      parent.replaceChild(n, emptyStringNode);
      break;

    case 1:
      Node foldedStringNode = arrayFoldedChildren.remove(0);
      if (foldedSize > originalSize) {
        return;
      }
      arrayNode.detachChildren();
      if (foldedStringNode.getType() != Token.STRING) {
        // If the Node is not a string literal, ensure that
        // it is coerced to a string.
        Node replacement = new Node(Token.ADD,
            Node.newString(""), foldedStringNode);
        foldedStringNode = replacement;
      }
      parent.replaceChild(n, foldedStringNode);
      break;

    default:
      // No folding could actually be performed.
      if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {
        return;
      }
      int kJoinOverhead = "[].join()".length();
      foldedSize += kJoinOverhead;
      foldedSize += InlineCostEstimator.getCost(right);
      if (foldedSize > originalSize) {
        return;
      }
      arrayNode.detachChildren();
      for (Node node : arrayFoldedChildren) {
        arrayNode.addChildToBack(node);
      }
      break;
  }
  t.getCompiler().reportCodeChange();
}
 
Example 7
Source File: Closure_61_NodeUtil_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the boolean value of a node that represents a literal. This method
 * effectively emulates the <code>Boolean()</code> JavaScript cast function
 * except it return UNKNOWN for known values with side-effects, use
 * getExpressionBooleanValue if you don't care about side-effects.
 */
static TernaryValue getPureBooleanValue(Node n) {
  switch (n.getType()) {
    case Token.STRING:
      return TernaryValue.forBoolean(n.getString().length() > 0);

    case Token.NUMBER:
      return TernaryValue.forBoolean(n.getDouble() != 0);

    case Token.NOT:
      return getPureBooleanValue(n.getLastChild()).not();

    case Token.NULL:
    case Token.FALSE:
    case Token.VOID:
      return TernaryValue.FALSE;

    case Token.NAME:
      String name = n.getString();
      if ("undefined".equals(name)
          || "NaN".equals(name)) {
        // We assume here that programs don't change the value of the keyword
        // undefined to something other than the value undefined.
        return TernaryValue.FALSE;
      } else if ("Infinity".equals(name)) {
        return TernaryValue.TRUE;
      }
      break;

    case Token.TRUE:
    case Token.REGEXP:
      return TernaryValue.TRUE;

    case Token.ARRAYLIT:
    case Token.OBJECTLIT:
      if (!mayHaveSideEffects(n)) {
        return TernaryValue.TRUE;
      }
  }

  return TernaryValue.UNKNOWN;
}
 
Example 8
Source File: Cardumen_00200_t.java    From coming with MIT License 4 votes vote down vote up
static int precedence(int type) {
  switch (type) {
    case Token.COMMA:  return 0;
    case Token.ASSIGN_BITOR:
    case Token.ASSIGN_BITXOR:
    case Token.ASSIGN_BITAND:
    case Token.ASSIGN_LSH:
    case Token.ASSIGN_RSH:
    case Token.ASSIGN_URSH:
    case Token.ASSIGN_ADD:
    case Token.ASSIGN_SUB:
    case Token.ASSIGN_MUL:
    case Token.ASSIGN_DIV:
    case Token.ASSIGN_MOD:
    case Token.ASSIGN: return 1;
    case Token.HOOK:   return 2;  // ?: operator
    case Token.OR:     return 3;
    case Token.AND:    return 4;
    case Token.BITOR:  return 5;
    case Token.BITXOR: return 6;
    case Token.BITAND: return 7;
    case Token.EQ:
    case Token.NE:
    case Token.SHEQ:
    case Token.SHNE:   return 8;
    case Token.LT:
    case Token.GT:
    case Token.LE:
    case Token.GE:
    case Token.INSTANCEOF:
    case Token.IN:     return 9;
    case Token.LSH:
    case Token.RSH:
    case Token.URSH:   return 10;
    case Token.SUB:
    case Token.ADD:    return 11;
    case Token.MUL:
    case Token.MOD:
    case Token.DIV:    return 12;
    case Token.INC:
    case Token.DEC:
    case Token.NEW:
    case Token.DELPROP:
    case Token.TYPEOF:
    case Token.VOID:
    case Token.NOT:
    case Token.BITNOT:
    case Token.POS:
    case Token.NEG:    return 13;

    case Token.CALL:
    case Token.GETELEM:
    case Token.GETPROP:
    // Data values
    case Token.ARRAYLIT:
    case Token.EMPTY:  // TODO(johnlenz): remove this.
    case Token.FALSE:
    case Token.FUNCTION:
    case Token.NAME:
    case Token.NULL:
    case Token.NUMBER:
    case Token.OBJECTLIT:
    case Token.REGEXP:
    case Token.STRING:
    case Token.STRING_KEY:
    case Token.THIS:
    case Token.TRUE:
      return 15;

    default: throw new Error("Unknown precedence for " +
                             Token.name(type) +
                             " (type " + type + ")");
  }
}
 
Example 9
Source File: jMutRepair_003_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * @param locals A predicate to apply to unknown local values.
 * @return Whether the node is known to be a value that is not a reference
 *     outside the expression scope.
 */
static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) {
  switch (value.getType()) {
    case Token.ASSIGN:
      // A result that is aliased by a non-local name, is the effectively the
      // same as returning a non-local name, but this doesn't matter if the
      // value is immutable.
      return NodeUtil.isImmutableValue(value.getLastChild())
          || (locals.apply(value)
              && evaluatesToLocalValue(value.getLastChild(), locals));
    case Token.COMMA:
      return evaluatesToLocalValue(value.getLastChild(), locals);
    case Token.AND:
    case Token.OR:
      return evaluatesToLocalValue(value.getFirstChild(), locals)
         && evaluatesToLocalValue(value.getLastChild(), locals);
    case Token.HOOK:
      return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)
         && evaluatesToLocalValue(value.getLastChild(), locals);
    case Token.INC:
    case Token.DEC:
      if (value.getBooleanProp(Node.INCRDECR_PROP)) {
        return evaluatesToLocalValue(value.getFirstChild(), locals);
      } else {
        return true;
      }
    case Token.THIS:
      return locals.apply(value);
    case Token.NAME:
      return isImmutableValue(value) || locals.apply(value);
    case Token.GETELEM:
    case Token.GETPROP:
      // There is no information about the locality of object properties.
      return locals.apply(value);
    case Token.CALL:
      return callHasLocalResult(value)
          || isToStringMethodCall(value)
          || locals.apply(value);
    case Token.NEW:
      return newHasLocalResult(value)
             || locals.apply(value);
    case Token.FUNCTION:
    case Token.REGEXP:
    case Token.ARRAYLIT:
    case Token.OBJECTLIT:
      // Literals objects with non-literal children are allowed.
      return true;
    case Token.DELPROP:
    case Token.IN:
      // TODO(johnlenz): should IN operator be included in #isSimpleOperator?
      return true;
    default:
      // Other op force a local value:
      //  x = '' + g (x is now an local string)
      //  x -= g (x is now an local number)
      if (isAssignmentOp(value)
          || isSimpleOperator(value)
          || isImmutableValue(value)) {
        return true;
      }

      throw new IllegalStateException(
          "Unexpected expression node" + value +
          "\n parent:" + value.getParent());
  }
}
 
Example 10
Source File: jKali_003_s.java    From coming with MIT License 4 votes vote down vote up
static int precedence(int type) {
  switch (type) {
    case Token.COMMA:  return 0;
    case Token.ASSIGN_BITOR:
    case Token.ASSIGN_BITXOR:
    case Token.ASSIGN_BITAND:
    case Token.ASSIGN_LSH:
    case Token.ASSIGN_RSH:
    case Token.ASSIGN_URSH:
    case Token.ASSIGN_ADD:
    case Token.ASSIGN_SUB:
    case Token.ASSIGN_MUL:
    case Token.ASSIGN_DIV:
    case Token.ASSIGN_MOD:
    case Token.ASSIGN: return 1;
    case Token.HOOK:   return 2;  // ?: operator
    case Token.OR:     return 3;
    case Token.AND:    return 4;
    case Token.BITOR:  return 5;
    case Token.BITXOR: return 6;
    case Token.BITAND: return 7;
    case Token.EQ:
    case Token.NE:
    case Token.SHEQ:
    case Token.SHNE:   return 8;
    case Token.LT:
    case Token.GT:
    case Token.LE:
    case Token.GE:
    case Token.INSTANCEOF:
    case Token.IN:     return 9;
    case Token.LSH:
    case Token.RSH:
    case Token.URSH:   return 10;
    case Token.SUB:
    case Token.ADD:    return 11;
    case Token.MUL:
    case Token.MOD:
    case Token.DIV:    return 12;
    case Token.INC:
    case Token.DEC:
    case Token.NEW:
    case Token.DELPROP:
    case Token.TYPEOF:
    case Token.VOID:
    case Token.NOT:
    case Token.BITNOT:
    case Token.POS:
    case Token.NEG:    return 13;

    case Token.CALL:
    case Token.GETELEM:
    case Token.GETPROP:
    // Data values
    case Token.ARRAYLIT:
    case Token.EMPTY:  // TODO(johnlenz): remove this.
    case Token.FALSE:
    case Token.FUNCTION:
    case Token.NAME:
    case Token.NULL:
    case Token.NUMBER:
    case Token.OBJECTLIT:
    case Token.REGEXP:
    case Token.STRING:
    case Token.STRING_KEY:
    case Token.THIS:
    case Token.TRUE:
      return 15;

    default: throw new Error("Unknown precedence for " +
                             Token.name(type) +
                             " (type " + type + ")");
  }
}
 
Example 11
Source File: Cardumen_0014_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the value of a node as a Number, or null if it cannot be converted.
 * When it returns a non-null Double, this method effectively emulates the
 * <code>Number()</code> JavaScript cast function.
 */
static Double getNumberValue(Node n) {
  switch (n.getType()) {
    case Token.TRUE:
      return 1.0;

    case Token.FALSE:
    case Token.NULL:
      return 0.0;

    case Token.NUMBER:
      return n.getDouble();

    case Token.VOID:
      if (mayHaveSideEffects(n.getFirstChild())) {
        return null;
      } else {
        return Double.NaN;
      }

    case Token.NAME:
      // Check for known constants
      String name = n.getString();
      if (name.equals("undefined")) {
        return Double.NaN;
      }
      if (name.equals("NaN")) {
        return Double.NaN;
      }
      if (name.equals("Infinity")) {
        return Double.POSITIVE_INFINITY;
      }
      return null;

    case Token.NEG:
      if (n.getChildCount() == 1 && n.getFirstChild().isName()
          && n.getFirstChild().getString().equals("Infinity")) {
        return Double.NEGATIVE_INFINITY;
      }
      return null;

    case Token.NOT:
      TernaryValue child = getPureBooleanValue(n.getFirstChild());
      if (child != TernaryValue.UNKNOWN) {
        return child.toBoolean(true) ? 0.0 : 1.0; // reversed.
      }
      break;

    case Token.STRING:
      return getStringNumberValue(n.getString());

    case Token.ARRAYLIT:
    case Token.OBJECTLIT:
      String value = getStringValue(n);
      return value != null ? getStringNumberValue(value) : null;
  }

  return null;
}
 
Example 12
Source File: jKali_003_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the value of a node as a String, or null if it cannot be converted.
 * When it returns a non-null String, this method effectively emulates the
 * <code>String()</code> JavaScript cast function.
 */
static String getStringValue(Node n) {
  // TODO(user): regex literals as well.
  switch (n.getType()) {
    case Token.STRING:
    case Token.STRING_KEY:
      return n.getString();

    case Token.NAME:
      String name = n.getString();
      if ("undefined".equals(name)
          || "Infinity".equals(name)
          || "NaN".equals(name)) {
        return name;
      }
      break;

    case Token.NUMBER:
      return getStringValue(n.getDouble());

    case Token.FALSE:
      return "false";

    case Token.TRUE:
      return "true";

    case Token.NULL:
      return "null";

    case Token.VOID:
      return "undefined";

    case Token.NOT:
      TernaryValue child = getPureBooleanValue(n.getFirstChild());
      if (child != TernaryValue.UNKNOWN) {
        return child.toBoolean(true) ? "false" : "true"; // reversed.
      }
      break;

    case Token.ARRAYLIT:
      return arrayToString(n);

    case Token.OBJECTLIT:
      return "[object Object]";
  }
  return null;
}
 
Example 13
Source File: Closure_23_PeepholeFoldConstants_t.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 14
Source File: 1_NodeUtil.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
/**
   * @param locals A predicate to apply to unknown local values.
   * @return Whether the node is known to be a value that is not a reference
   *     outside the expression scope.
   */
  static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) {
    switch (value.getType()) {
      case Token.ASSIGN:
        // A result that is aliased by a non-local name, is the effectively the
        // same as returning a non-local name, but this doesn't matter if the
        // value is immutable.
        return NodeUtil.isImmutableValue(value.getLastChild())
            || (locals.apply(value)
                && evaluatesToLocalValue(value.getLastChild(), locals));
      case Token.COMMA:
        return evaluatesToLocalValue(value.getLastChild(), locals);
      case Token.AND:
      case Token.OR:
        return evaluatesToLocalValue(value.getFirstChild(), locals)
           && evaluatesToLocalValue(value.getLastChild(), locals);
      case Token.HOOK:
        return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)
           && evaluatesToLocalValue(value.getLastChild(), locals);
      case Token.INC:
      case Token.DEC:
        if (value.getBooleanProp(Node.INCRDECR_PROP)) {
          return evaluatesToLocalValue(value.getFirstChild(), locals);
        } else {
          return true;
        }
      case Token.THIS:
        return locals.apply(value);
      case Token.NAME:
        return isImmutableValue(value) || locals.apply(value);
      case Token.GETELEM:
      case Token.GETPROP:
        // There is no information about the locality of object properties.
        return locals.apply(value);
      case Token.CALL:
        return callHasLocalResult(value)
            || isToStringMethodCall(value)
            || locals.apply(value);
      case Token.NEW:
        return newHasLocalResult(value)
               || locals.apply(value);
      case Token.FUNCTION:
      case Token.REGEXP:
      case Token.ARRAYLIT:
      case Token.OBJECTLIT:
        // Literals objects with non-literal children are allowed.
        return true;
      case Token.IN:
        // TODO(johnlenz): should IN operator be included in #isSimpleOperator?
        return true;
      default:
        // Other op force a local value:
        //  x = '' + g (x is now an local string)
        //  x -= g (x is now an local number)
// start of generated patch
if(!value.getBooleanProp(Node.IS_NAMESPACE)){
return true;
}
// end of generated patch
/* start of original code
        if (isAssignmentOp(value)
            || isSimpleOperator(value)
            || isImmutableValue(value)) {
          return true;
        }
 end of original code*/

        throw new IllegalStateException(
            "Unexpected expression node" + value +
            "\n parent:" + value.getParent());
    }
  }
 
Example 15
Source File: Closure_10_NodeUtil_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the value of a node as a String, or null if it cannot be converted.
 * When it returns a non-null String, this method effectively emulates the
 * <code>String()</code> JavaScript cast function.
 */
static String getStringValue(Node n) {
  // TODO(user): regex literals as well.
  switch (n.getType()) {
    case Token.STRING:
    case Token.STRING_KEY:
      return n.getString();

    case Token.NAME:
      String name = n.getString();
      if ("undefined".equals(name)
          || "Infinity".equals(name)
          || "NaN".equals(name)) {
        return name;
      }
      break;

    case Token.NUMBER:
      return getStringValue(n.getDouble());

    case Token.FALSE:
      return "false";

    case Token.TRUE:
      return "true";

    case Token.NULL:
      return "null";

    case Token.VOID:
      return "undefined";

    case Token.NOT:
      TernaryValue child = getPureBooleanValue(n.getFirstChild());
      if (child != TernaryValue.UNKNOWN) {
        return child.toBoolean(true) ? "false" : "true"; // reversed.
      }
      break;

    case Token.ARRAYLIT:
      return arrayToString(n);

    case Token.OBJECTLIT:
      return "[object Object]";
  }
  return null;
}
 
Example 16
Source File: Closure_75_NodeUtil_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the boolean value of a node that represents a literal. This method
 * effectively emulates the <code>Boolean()</code> JavaScript cast function
 * except it return UNKNOWN for known values with side-effects, use
 * getExpressionBooleanValue if you don't care about side-effects.
 */
static TernaryValue getPureBooleanValue(Node n) {
  switch (n.getType()) {
    case Token.STRING:
      return TernaryValue.forBoolean(n.getString().length() > 0);

    case Token.NUMBER:
      return TernaryValue.forBoolean(n.getDouble() != 0);

    case Token.NOT:
      return getPureBooleanValue(n.getLastChild()).not();

    case Token.NULL:
    case Token.FALSE:
    case Token.VOID:
      return TernaryValue.FALSE;

    case Token.NAME:
      String name = n.getString();
      if ("undefined".equals(name)
          || "NaN".equals(name)) {
        // We assume here that programs don't change the value of the keyword
        // undefined to something other than the value undefined.
        return TernaryValue.FALSE;
      } else if ("Infinity".equals(name)) {
        return TernaryValue.TRUE;
      }
      break;

    case Token.TRUE:
    case Token.REGEXP:
      return TernaryValue.TRUE;

    case Token.ARRAYLIT:
    case Token.OBJECTLIT:
      if (!mayHaveSideEffects(n)) {
        return TernaryValue.TRUE;
      }
  }

  return TernaryValue.UNKNOWN;
}
 
Example 17
Source File: Cardumen_0014_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * @param locals A predicate to apply to unknown local values.
 * @return Whether the node is known to be a value that is not a reference
 *     outside the expression scope.
 */
static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) {
  switch (value.getType()) {
    case Token.ASSIGN:
      // A result that is aliased by a non-local name, is the effectively the
      // same as returning a non-local name, but this doesn't matter if the
      // value is immutable.
      return NodeUtil.isImmutableValue(value.getLastChild())
          || (locals.apply(value)
              && evaluatesToLocalValue(value.getLastChild(), locals));
    case Token.COMMA:
      return evaluatesToLocalValue(value.getLastChild(), locals);
    case Token.AND:
    case Token.OR:
      return evaluatesToLocalValue(value.getFirstChild(), locals)
         && evaluatesToLocalValue(value.getLastChild(), locals);
    case Token.HOOK:
      return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)
         && evaluatesToLocalValue(value.getLastChild(), locals);
    case Token.INC:
    case Token.DEC:
      if (value.getBooleanProp(Node.INCRDECR_PROP)) {
        return evaluatesToLocalValue(value.getFirstChild(), locals);
      } else {
        return true;
      }
    case Token.THIS:
      return locals.apply(value);
    case Token.NAME:
      return isImmutableValue(value) || locals.apply(value);
    case Token.GETELEM:
    case Token.GETPROP:
      // There is no information about the locality of object properties.
      return locals.apply(value);
    case Token.CALL:
      return callHasLocalResult(value)
          || isToStringMethodCall(value)
          || locals.apply(value);
    case Token.NEW:
      return newHasLocalResult(value)
             || locals.apply(value);
    case Token.FUNCTION:
    case Token.REGEXP:
    case Token.ARRAYLIT:
    case Token.OBJECTLIT:
      // Literals objects with non-literal children are allowed.
      return true;
    case Token.DELPROP:
    case Token.IN:
      // TODO(johnlenz): should IN operator be included in #isSimpleOperator?
      return true;
    default:
      // Other op force a local value:
      //  x = '' + g (x is now an local string)
      //  x -= g (x is now an local number)
      if (isAssignmentOp(value)
          || isSimpleOperator(value)
          || isImmutableValue(value)) {
        return true;
      }

      throw new IllegalStateException(
          "Unexpected expression node" + value +
          "\n parent:" + value.getParent());
  }
}
 
Example 18
Source File: Cardumen_00149_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the boolean value of a node that represents a literal. This method
 * effectively emulates the <code>Boolean()</code> JavaScript cast function
 * except it return UNKNOWN for known values with side-effects, use
 * getExpressionBooleanValue if you don't care about side-effects.
 */
static TernaryValue getPureBooleanValue(Node n) {
  switch (n.getType()) {
    case Token.STRING:
      return TernaryValue.forBoolean(n.getString().length() > 0);

    case Token.NUMBER:
      return TernaryValue.forBoolean(n.getDouble() != 0);

    case Token.NOT:
      return getPureBooleanValue(n.getLastChild()).not();

    case Token.NULL:
    case Token.FALSE:
      return TernaryValue.FALSE;

    case Token.VOID:
      if (!mayHaveSideEffects(n.getFirstChild())) {
        return TernaryValue.FALSE;
      }
      break;

    case Token.NAME:
      String name = n.getString();
      if ("undefined".equals(name)
          || "NaN".equals(name)) {
        // We assume here that programs don't change the value of the keyword
        // undefined to something other than the value undefined.
        return TernaryValue.FALSE;
      } else if ("Infinity".equals(name)) {
        return TernaryValue.TRUE;
      }
      break;

    case Token.TRUE:
    case Token.REGEXP:
      return TernaryValue.TRUE;

    case Token.ARRAYLIT:
    case Token.OBJECTLIT:
      if (!mayHaveSideEffects(n)) {
        return TernaryValue.TRUE;
      }
      break;
  }

  return TernaryValue.UNKNOWN;
}
 
Example 19
Source File: 1_NodeUtil.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets the value of a node as a String, or null if it cannot be converted.
 * When it returns a non-null String, this method effectively emulates the
 * <code>String()</code> JavaScript cast function.
 */
static String getStringValue(Node n) {
  // TODO(user): regex literals as well.
  switch (n.getType()) {
    case Token.STRING:
      return n.getString();

    case Token.NAME:
      String name = n.getString();
      if ("undefined".equals(name)
          || "Infinity".equals(name)
          || "NaN".equals(name)) {
        return name;
      }
      break;

    case Token.NUMBER:
      double value = n.getDouble();
      long longValue = (long) value;

      // Return "1" instead of "1.0"
      if (longValue == value) {
        return Long.toString(longValue);
      } else {
        return Double.toString(n.getDouble());
      }

    case Token.FALSE:
    case Token.TRUE:
    case Token.NULL:
      return Node.tokenToName(n.getType());

    case Token.VOID:
      return "undefined";

    case Token.NOT:
      TernaryValue child = getBooleanValue(n.getFirstChild());
      if (child != TernaryValue.UNKNOWN) {
        return child.toBoolean(true) ? "false" : "true"; // reversed.
      }
      break;

    case Token.ARRAYLIT:
      return arrayToString(n);

    case Token.OBJECTLIT:
      return "[object Object]";
  }
  return null;
}
 
Example 20
Source File: Closure_75_NodeUtil_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Is this an ARRAYLIT node
 */
static boolean isArrayLiteral(Node node) {
  return node.getType() == Token.ARRAYLIT;
}