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

The following examples show how to use com.google.javascript.rhino.Node#getString() . 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_75_NodeUtil_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Returns true if this is an immutable value.
 */
static boolean isImmutableValue(Node n) {
  switch (n.getType()) {
    case Token.STRING:
    case Token.NUMBER:
    case Token.NULL:
    case Token.TRUE:
    case Token.FALSE:
      return true;
    case Token.NOT:
      return isImmutableValue(n.getFirstChild());
    case Token.VOID:
    case Token.NEG:
      return isImmutableValue(n.getFirstChild());
    case Token.NAME:
      String name = n.getString();
      // We assume here that programs don't change the value of the keyword
      // undefined to something other than the value undefined.
      return "undefined".equals(name)
          || "Infinity".equals(name)
          || "NaN".equals(name);
  }

  return false;
}
 
Example 2
Source File: Closure_86_NodeUtil_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets the function's name. This method recognizes five forms:
 * <ul>
 * <li>{@code function name() ...}</li>
 * <li>{@code var name = function() ...}</li>
 * <li>{@code qualified.name = function() ...}</li>
 * <li>{@code var name2 = function name1() ...}</li>
 * <li>{@code qualified.name2 = function name1() ...}</li>
 * </ul>
 * In two last cases with named function expressions, the second name is
 * returned (the variable of qualified name).
 *
 * @param n a node whose type is {@link Token#FUNCTION}
 * @return the function's name, or {@code null} if it has no name
 */
static String getFunctionName(Node n) {
  Node parent = n.getParent();
  String name = n.getFirstChild().getString();
  switch (parent.getType()) {
    case Token.NAME:
      // var name = function() ...
      // var name2 = function name1() ...
      return parent.getString();

    case Token.ASSIGN:
      // qualified.name = function() ...
      // qualified.name2 = function name1() ...
      return parent.getFirstChild().getQualifiedName();

    default:
      // function name() ...
      return name != null && name.length() != 0 ? name : null;
  }
}
 
Example 3
Source File: Closure_70_TypedScopeCreator_t.java    From coming with MIT License 6 votes vote down vote up
/** Handle bleeding functions and function parameters. */
private void handleFunctionInputs(Node fnNode) {
  // Handle bleeding functions.
  Node fnNameNode = fnNode.getFirstChild();
  String fnName = fnNameNode.getString();
  if (!fnName.isEmpty()) {
    Scope.Var fnVar = scope.getVar(fnName);
    if (fnVar == null ||
        // Make sure we're not touching a native function. Native
        // functions aren't bleeding, but may not have a declaration
        // node.
        (fnVar.getNameNode() != null &&
            // Make sure that the function is actually bleeding by checking
            // if has already been declared.
            fnVar.getInitialValue() != fnNode)) {
      defineSlot(fnNameNode, fnNode, fnNode.getJSType(), false);
    }
  }

  declareArguments(fnNode);
}
 
Example 4
Source File: Closure_86_NodeUtil_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets the function's name. This method recognizes five forms:
 * <ul>
 * <li>{@code function name() ...}</li>
 * <li>{@code var name = function() ...}</li>
 * <li>{@code qualified.name = function() ...}</li>
 * <li>{@code var name2 = function name1() ...}</li>
 * <li>{@code qualified.name2 = function name1() ...}</li>
 * </ul>
 * In two last cases with named function expressions, the second name is
 * returned (the variable of qualified name).
 *
 * @param n a node whose type is {@link Token#FUNCTION}
 * @return the function's name, or {@code null} if it has no name
 */
static String getFunctionName(Node n) {
  Node parent = n.getParent();
  String name = n.getFirstChild().getString();
  switch (parent.getType()) {
    case Token.NAME:
      // var name = function() ...
      // var name2 = function name1() ...
      return parent.getString();

    case Token.ASSIGN:
      // qualified.name = function() ...
      // qualified.name2 = function name1() ...
      return parent.getFirstChild().getQualifiedName();

    default:
      // function name() ...
      return name != null && name.length() != 0 ? name : null;
  }
}
 
Example 5
Source File: Cardumen_00200_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets the function's name. This method recognizes the forms:
 * <ul>
 * <li>{@code &#123;'name': function() ...&#125;}</li>
 * <li>{@code &#123;name: function() ...&#125;}</li>
 * <li>{@code function name() ...}</li>
 * <li>{@code var name = function() ...}</li>
 * <li>{@code qualified.name = function() ...}</li>
 * <li>{@code var name2 = function name1() ...}</li>
 * <li>{@code qualified.name2 = function name1() ...}</li>
 * </ul>
 *
 * @param n a node whose type is {@link Token#FUNCTION}
 * @return the function's name, or {@code null} if it has no name
 */
public static String getNearestFunctionName(Node n) {
  if (!n.isFunction()) {
    return null;
  }

  String name = getFunctionName(n);
  if (name != null) {
    return name;
  }

  // Check for the form { 'x' : function() { } }
  Node parent = n.getParent();
  switch (parent.getType()) {
    case Token.SETTER_DEF:
    case Token.GETTER_DEF:
    case Token.STRING_KEY:
      // Return the name of the literal's key.
      return parent.getString();
    case Token.NUMBER:
      return getStringValue(parent);
  }

  return null;
}
 
Example 6
Source File: Closure_75_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/** Whether the given name is constant by coding convention. */
static boolean isConstantByConvention(
    CodingConvention convention, Node node, Node parent) {
  String name = node.getString();
  if (parent.getType() == Token.GETPROP &&
      node == parent.getLastChild()) {
    return convention.isConstantKey(name);
  } else if (isObjectLitKey(node, parent)) {
    return convention.isConstantKey(name);
  } else {
    return convention.isConstant(name);
  }
}
 
Example 7
Source File: Closure_114_NameAnalyzer_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Creates name information for a particular qualified name that occurs in a
 * particular scope.
 *
 * @param name A qualified name (e.g. "x" or "a.b.c")
 * @param scope The scope in which {@code name} occurs
 * @param rootNameNode The NAME node for the first token of {@code name}
 * @return The name information, or null if the name is irrelevant to this
 *     pass
 */
private NameInformation createNameInformation(
    String name, Scope scope, Node rootNameNode) {
  // Check the scope. Currently we're only looking at globally scoped vars.
  String rootName = rootNameNode.getString();
  Var v = scope.getVar(rootName);
  boolean isExtern = (v == null && externalNames.contains(rootName));
  boolean isGlobalRef = (v != null && v.isGlobal()) || isExtern ||
      rootName.equals(WINDOW);
  if (!isGlobalRef) {
    return null;
  }

  NameInformation nameInfo = new NameInformation();

  // If a prototype property or method, fill in prototype information.
  int idx = name.indexOf(PROTOTYPE_SUBSTRING);
  if (idx != -1) {
    nameInfo.isPrototype = true;
    nameInfo.prototypeClass = name.substring(0, idx);
    nameInfo.prototypeProperty = name.substring(
        idx + PROTOTYPE_SUBSTRING_LEN);
  }

  nameInfo.name = name;
  nameInfo.isExternallyReferenceable =
      isExtern || isExternallyReferenceable(scope, name);
  return nameInfo;
}
 
Example 8
Source File: AnonymousFunctionNamingCallback.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void nameObjectLiteralMethods(Node objectLiteral, String context) {
  for (Node keyNode = objectLiteral.getFirstChild();
       keyNode != null;
       keyNode = keyNode.getNext()) {
    Node valueNode = keyNode.getFirstChild();

    // Object literal keys may be STRING_KEY, GETTER_DEF, SETTER_DEF.
    // Get and Set are skipped because they can not be named.
    if (keyNode.isStringKey()) {
      // concatenate the context and key name to get a new qualified name.
      String name = namer.getCombinedName(context, namer.getName(keyNode));

      int type = valueNode.getType();
      if (type == Token.FUNCTION) {
        // set name if function is anonymous
        Node functionNameNode = valueNode.getFirstChild();
        String functionName = functionNameNode.getString();
        if (functionName.isEmpty()) {
          namer.setFunctionName(name, valueNode);
        }
      } else if (type == Token.OBJECTLIT) {
        // process nested object literal
        nameObjectLiteralMethods(valueNode, name);
      }
    }
  }
}
 
Example 9
Source File: Closure_10_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
@Override
public void visit(Node n) {
  if (n.isName()) {
    Node parent = n.getParent();
    if (parent != null && parent.isVar()) {
      String name = n.getString();
      if (!vars.containsKey(name)) {
        vars.put(name, n);
      }
    }
  }
}
 
Example 10
Source File: Closure_61_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return Whether node is a call to methodName.
 *    a.f(...)
 *    a['f'](...)
 */
static boolean isObjectCallMethod(Node callNode, String methodName) {
  if (callNode.getType() == Token.CALL) {
    Node functionIndentifyingExpression = callNode.getFirstChild();
    if (isGet(functionIndentifyingExpression)) {
      Node last = functionIndentifyingExpression.getLastChild();
      if (last != null && last.getType() == Token.STRING) {
        String propName = last.getString();
        return (propName.equals(methodName));
      }
    }
  }
  return false;
}
 
Example 11
Source File: Closure_67_AnalyzePrototypeProperties_t.java    From coming with MIT License 5 votes vote down vote up
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
  if (isPrototypePropertyAssign(n)) {
    symbolStack.push(new NameContext(getNameInfoForName(
            n.getFirstChild().getLastChild().getString(), PROPERTY)));
  } else if (isGlobalFunctionDeclaration(t, n)) {
    String name = parent.getType() == Token.NAME ?
        parent.getString() /* VAR */ :
        n.getFirstChild().getString() /* named function */;
    symbolStack.push(new NameContext(getNameInfoForName(name, VAR)));
  } else if (NodeUtil.isFunction(n)) {
    symbolStack.push(new NameContext(anonymousNode));
  }
  return true;
}
 
Example 12
Source File: Closure_75_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Get the name of an object literal key.
 *
 * @param key A node
 */
static String getObjectLitKeyName(Node key) {
  switch (key.getType()) {
    case Token.NUMBER:
      return NodeUtil.getStringValue(key);
    case Token.STRING:
    case Token.GET:
    case Token.SET:
      return key.getString();
  }
  throw new IllegalStateException("Unexpected node type: " + key);
}
 
Example 13
Source File: RenameProperties.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * If a property node is eligible for renaming, stashes a reference to it
 * and increments the property name's access count.
 *
 * @param n The STRING node for a property
 */
private void maybeMarkCandidate(Node n) {
  String name = n.getString();
  if (!externedNames.contains(name)) {
    stringNodesToRename.add(n);
    countPropertyOccurrence(name);
  }
}
 
Example 14
Source File: Closure_128_CodeGenerator_s.java    From coming with MIT License 5 votes vote down vote up
/** Outputs a JS string, using the optimal (single/double) quote character */
private void addJsString(Node n) {
  String s = n.getString();
  boolean useSlashV = n.getBooleanProp(Node.SLASH_V);
  if (useSlashV) {
    add(jsString(n.getString(), useSlashV));
  } else {
    String cached = ESCAPED_JS_STRINGS.get(s);
    if (cached == null) {
      cached = jsString(n.getString(), useSlashV);
      ESCAPED_JS_STRINGS.put(s, cached);
    }
    add(cached);
  }
}
 
Example 15
Source File: Closure_61_NodeUtil_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:
    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 16
Source File: Nopol2017_0014_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Gets the fully qualified name corresponding to an object literal key,
 * as long as it and its prefix property names are valid JavaScript
 * identifiers. The object literal may be nested inside of other object
 * literals.
 *
 * For example, if called with node {@code n} representing "z" in any of
 * the following expressions, the result would be "w.x.y.z":
 * <code> var w = {x: {y: {z: 0}}}; </code>
 * <code> w.x = {y: {z: 0}}; </code>
 * <code> w.x.y = {'a': 0, 'z': 0}; </code>
 *
 * @param n A child of an OBJLIT node
 * @return The global name, or null if {@code n} doesn't correspond to the
 *   key of an object literal that can be named
 */
String getNameForObjLitKey(Node n) {
  Node parent = n.getParent();
  Preconditions.checkState(parent.isObjectLit());

  Node gramps = parent.getParent();
  if (gramps == null) {
    return null;
  }

  Node greatGramps = gramps.getParent();
  String name;
  switch (gramps.getType()) {
    case Token.NAME:
      // VAR
      //   NAME (gramps)
      //     OBJLIT (parent)
      //       STRING (n)
      if (greatGramps == null || !greatGramps.isVar()) {
        return null;
      }
      name = gramps.getString();
      break;
    case Token.ASSIGN:
      // ASSIGN (gramps)
      //   NAME|GETPROP
      //   OBJLIT (parent)
      //     STRING (n)
      Node lvalue = gramps.getFirstChild();
      name = lvalue.getQualifiedName();
      break;
    case Token.STRING_KEY:
      // OBJLIT
      //   STRING (gramps)
      //     OBJLIT (parent)
      //       STRING (n)
      if (greatGramps != null &&
          greatGramps.isObjectLit()) {
        name = getNameForObjLitKey(gramps);
      } else {
        return null;
      }
      break;
    default:
      return null;
  }
  if (name != null) {
    String key = n.getString();
    if (TokenStream.isJSIdentifier(key)) {
      return name + '.' + key;
    }
  }
  return null;
}
 
Example 17
Source File: Cardumen_00149_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 18
Source File: Closure_50_PeepholeReplaceKnownMethods_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Try to evaluate known String methods
 *    .indexOf(), .substr(), .substring()
 */
private Node tryFoldKnownStringMethods(Node subtree) {
  Preconditions.checkArgument(subtree.getType() == Token.CALL);

  // check if this is a call on a string method
  // then dispatch to specific folding method.
  Node callTarget = subtree.getFirstChild();
  if (callTarget == null) {
    return subtree;
  }

  if (!NodeUtil.isGet(callTarget)) {
    return subtree;
  }

  Node stringNode = callTarget.getFirstChild();
  Node functionName = stringNode.getNext();

  if ((stringNode.getType() != Token.STRING) ||
      (functionName.getType() != Token.STRING)) {
    return subtree;
  }

  String functionNameString = functionName.getString();
  Node firstArg = callTarget.getNext();
  if (firstArg == null) {
    if (functionNameString.equals("toLowerCase")) {
      subtree = tryFoldStringToLowerCase(subtree, stringNode);
    } else if (functionNameString.equals("toUpperCase")) {
      subtree = tryFoldStringToUpperCase(subtree, stringNode);
    }
    return subtree;
  } else if (NodeUtil.isImmutableValue(firstArg)) {
    if (functionNameString.equals("indexOf") ||
        functionNameString.equals("lastIndexOf")) {
      subtree = tryFoldStringIndexOf(subtree, functionNameString,
          stringNode, firstArg);
    } else if (functionNameString.equals("substr")) {
      subtree = tryFoldStringSubstr(subtree, stringNode, firstArg);
    } else if (functionNameString.equals("substring")) {
      subtree = tryFoldStringSubstring(subtree, stringNode, firstArg);
    } else if (functionNameString.equals("charAt")) {
      subtree = tryFoldStringCharAt(subtree, stringNode, firstArg);
    } else if (functionNameString.equals("charCodeAt")) {
      subtree = tryFoldStringCharCodeAt(subtree, stringNode, firstArg);
    }
  }

  return subtree;
}
 
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_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;
}