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

The following are Jave code examples for showing how to use getFirstChild() of the com.google.javascript.rhino.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: feedlack   File: FoldConstants.java   View Source Code Vote up 6 votes
/**
 * Reduce "return undefined" or "return void 0" to simply "return".
 */
private void tryReduceReturn(NodeTraversal t, Node n) {
  Node result = n.getFirstChild();
  if (result != null) {
    switch (result.getType()) {
      case Token.VOID:
        Node operand = result.getFirstChild();
        if (!NodeUtil.mayHaveSideEffects(operand)) {
          n.removeFirstChild();
          t.getCompiler().reportCodeChange();
        }
        return;
      case Token.NAME:
        String name = result.getString();
        if (name.equals("undefined")) {
          n.removeFirstChild();
          t.getCompiler().reportCodeChange();
        }
        return;
    }
  }
}
 
Example 2
Project: feedlack   File: ParserTest.java   View Source Code Vote up 6 votes
public void testLinenoCharnoArrayLiteral() throws Exception {
  Node n = parse("\n  [8, 9]").getFirstChild().getFirstChild();

  assertEquals(Token.ARRAYLIT, n.getType());
  assertEquals(2, n.getLineno());
  assertEquals(2, n.getCharno());

  n = n.getFirstChild();

  assertEquals(Token.NUMBER, n.getType());
  assertEquals(2, n.getLineno());
  assertEquals(3, n.getCharno());

  n = n.getNext();

  assertEquals(Token.NUMBER, n.getType());
  assertEquals(2, n.getLineno());
  assertEquals(6, n.getCharno());
}
 
Example 3
Project: feedlack   File: CheckAccessControls.java   View Source Code Vote up 6 votes
/**
 * Determines whether a deprecation warning should be emitted.
 * @param t The current traversal.
 * @param n The node which we are checking.
 * @param parent The parent of the node which we are checking.
 */
private boolean shouldEmitDeprecationWarning(
    NodeTraversal t, Node n, Node parent) {
  // In the global scope, there are only two kinds of accesses that should
  // be flagged for warnings:
  // 1) Calls of deprecated functions and methods.
  // 2) Instantiations of deprecated classes.
  // For now, we just let everything else by.
  if (t.inGlobalScope()) {
    if (!((parent.getType() == Token.CALL && parent.getFirstChild() == n) ||
            n.getType() == Token.NEW)) {
      return false;
    }
  }

  // We can always assign to a deprecated property, to keep it up to date.
  if (n.getType() == Token.GETPROP && n == parent.getFirstChild() &&
      NodeUtil.isAssignmentOp(parent)) {
    return false;
  }

  return !canAccessDeprecatedTypes(t);
}
 
Example 4
Project: feedlack   File: SimpleDefinitionFinder.java   View Source Code Vote up 6 votes
@Override
public Collection<Definition> getDefinitionsReferencedAt(Node useSite) {
  if (definitionSiteMap.containsKey(useSite)) {
    return null;
  }

  if (NodeUtil.isGetProp(useSite)) {
    String propName = useSite.getLastChild().getString();
    if (propName.equals("apply") || propName.equals("call")) {
      useSite = useSite.getFirstChild();
    }
  }

  String name = getSimplifiedName(useSite);
  if (name != null) {
    Collection<Definition> defs = nameDefinitionMultimap.get(name);
    if (!defs.isEmpty()) {
      return defs;
    } else {
      return null;
    }
  } else {
    return null;
  }
}
 
Example 5
Project: feedlack   File: FunctionToBlockMutator.java   View Source Code Vote up 6 votes
/**
 *  For all VAR node with uninitialized declarations, set
 *  the values to be "undefined".
 */
private void fixUnitializedVarDeclarations(Node n) {
  // Inner loop structure must already have logic to initialize its
  // variables.  In particular FOR-IN structures must not be modified.
  if (NodeUtil.isLoopStructure(n)) {
    return;
  }

  // For all VARs
  if (NodeUtil.isVar(n)) {
    Node name = n.getFirstChild();
    // It isn't initialized.
    if (!name.hasChildren()) {
      name.addChildToBack(NodeUtil.newUndefinedNode());
    }
    return;
  }

  for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
    fixUnitializedVarDeclarations(c);
  }
}
 
Example 6
Project: feedlack   File: AliasKeywords.java   View Source Code Vote up 6 votes
/**
 * Does the given node define one of our aliases?
 */
private boolean isAliasDefinition(Node n) {
  if (n.getType() != Token.NAME) {
    return false;
  }

  if (!isAliasName(n.getString())) {
    // The given Node's string contents is not an alias. Skip it.
    return false;
  }

  /*
   * A definition must have a child node (otherwise it's just a
   * reference to the alias).
   */
  return n.getFirstChild() != null;
}
 
Example 7
Project: feedlack   File: StripCode.java   View Source Code Vote up 6 votes
/**
 * Eliminates any object literal keys in an object literal declaration that
 * have strip names.
 *
 * @param t The traversal
 * @param n An OBJLIT node
 */
void eliminateKeysWithStripNamesFromObjLit(NodeTraversal t, Node n) {
  // OBJLIT
  //   key1
  //   value1
  //   ...
  Node key = n.getFirstChild();
  while (key != null) {
    if (key.getType() == Token.STRING &&
        isStripName(key.getString())) {
      Node value = key.getNext();
      Node next = value.getNext();
      n.removeChild(key);
      n.removeChild(value);
      key = next;
      compiler.reportCodeChange();
    } else {
      key = key.getNext().getNext();
    }
  }
}
 
Example 8
Project: feedlack   File: AliasExternals.java   View Source Code Vote up 6 votes
private void replaceAccessor(Node getPropNode) {
  /*
   *  BEFORE
      getprop
          NODE...
          string length
      AFTER
      getelem
          NODE...
          name PROP_length
   */
  Node propNameNode = getPropNode.getLastChild();
  String propName = propNameNode.getString();
  if (props.get(propName).aliasAccessor) {
    Node propSrc = getPropNode.getFirstChild();
    getPropNode.removeChild(propSrc);

    Node newNameNode =
      Node.newString(Token.NAME, getArrayNotationNameFor(propName));

    Node elemNode = new Node(Token.GETELEM, propSrc, newNameNode);
    replaceNode(getPropNode.getParent(), getPropNode, elemNode);

    compiler.reportCodeChange();
  }
}
 
Example 9
Project: feedlack   File: NodeUtil.java   View Source Code Vote up 6 votes
/**
 * @return Whether the predicate is true for the node or any of its children.
 */
static boolean has(Node node,
                   Predicate<Node> pred,
                   Predicate<Node> traverseChildrenPred) {
  if (pred.apply(node)) {
    return true;
  }

  if (!traverseChildrenPred.apply(node)) {
    return false;
  }

  for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
    if (has(c, pred, traverseChildrenPred)) {
      return true;
    }
  }

  return false;
}
 
Example 10
Project: feedlack   File: NodeUtilTest.java   View Source Code Vote up 5 votes
public void testMergeBlock2() {
  Compiler compiler = new Compiler();

  // Test removing the initializer.
  Node actual = parse("foo:{a();}");

  Node parentLabel = actual.getFirstChild();
  Node childBlock = parentLabel.getLastChild();

  assertTrue(NodeUtil.tryMergeBlock(childBlock));
  String expected = "foo:a();";
  String difference = parse(expected).checkTreeEquals(actual);
  assertNull("Nodes do not match:\n" + difference, difference);
}
 
Example 11
Project: feedlack   File: IRFactoryTest.java   View Source Code Vote up 5 votes
public void testFunctionParamLocation() {
  Node root = newParse(
      "\nfunction\n" +
      "     foo(a,\n" +
      "     b,\n" +
      "     c)\n" +
      "{}\n");

  Node function = root.getFirstChild();
  Node functionName = function.getFirstChild();
  Node params = functionName.getNext();
  Node param1 = params.getFirstChild();
  Node param2 = param1.getNext();
  Node param3 = param2.getNext();
  Node body = params.getNext();

  assertNodePosition(2, 5, function);
  assertNodePosition(2, 5, functionName);
  // params corresponds to the LP token.
  // Can't be on a separate line because of inferred
  // semicolons.
  assertNodePosition(2, 8, params);
  assertNodePosition(2, 9, param1);
  assertNodePosition(3, 5, param2);
  assertNodePosition(4, 5, param3);
  assertNodePosition(5, 0, body);
}
 
Example 12
Project: feedlack   File: TightenTypes.java   View Source Code Vote up 5 votes
/**
 * Returns an action for assigning the right-hand-side to the left or null
 * if this assignment should be ignored.
 */
private List<Action> createAssignmentActions(
    Node lhs, Node rhs, Node parent) {
  switch (lhs.getType()) {
    case Token.NAME:
      ConcreteSlot var = (ConcreteSlot) scope.getSlot(lhs.getString());
      Preconditions.checkState(var != null,
          "Type tightener could not find variable with name %s",
          lhs.getString());
      return Lists.<Action>newArrayList(
          new VariableAssignAction(var, rhs));

    case Token.GETPROP:
      Node receiver = lhs.getFirstChild();
      return Lists.<Action>newArrayList(
          new PropertyAssignAction(receiver, rhs));

    case Token.GETELEM:
      return Lists.newArrayList();

    case Token.GET_REF:
      // We ignore ref specials as their types should not be computed.
      if (lhs.getFirstChild().getType() == Token.REF_SPECIAL) {
        return Lists.newArrayList();
      } else {
        throw new AssertionError(
            "Bad LHS for getref: " + parent.toStringTree());
      }

    default:
      throw new AssertionError(
          "Bad LHS for assignment: " + parent.toStringTree());
  }
}
 
Example 13
Project: feedlack   File: FunctionNames.java   View Source Code Vote up 5 votes
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.getType() == Token.FUNCTION) {
    Node functionNameNode = n.getFirstChild();
    String functionName = functionNameNode.getString();

    Node enclosingFunction = t.getEnclosingFunction();

    functionMap.put(n,
        new FunctionRecord(nextId, enclosingFunction, functionName));
    nextId++;
  }
}
 
Example 14
Project: feedlack   File: ExtractPrototypeMemberDeclarations.java   View Source Code Vote up 5 votes
/**
 * Replaces a member declaration to an assignment to the temp prototype
 * object.
 */
private void replacePrototypeMemberDeclaration(
    PrototypeMemberDeclaration declar) {
  // x.prototype.y = ...  ->  t.y = ...
  Node assignment = declar.node.getFirstChild();
  Node lhs = assignment.getFirstChild();
  Node name = NodeUtil.newQualifiedNameNode(
      prototypeAlias + "." + declar.memberName, declar.node,
      declar.memberName);

  // Save the full prototype path on the left hand side of the assignment
  // for debugging purposes.
  // declar.lhs = x.prototype.y so first child of the first child
  // is 'x'.
  Node accessNode = declar.lhs.getFirstChild().getFirstChild();
  Object originalName = accessNode.getProp(Node.ORIGINALNAME_PROP);

  String className = "?";

  if (originalName != null) {
    className = originalName.toString();
  }

  NodeUtil.setDebugInformation(name.getFirstChild(), lhs,
                               className + ".prototype");

  assignment.replaceChild(lhs, name);
}
 
Example 15
Project: feedlack   File: ParserTest.java   View Source Code Vote up 5 votes
public void testLinenoCharnoObjectLiteral() throws Exception {
  Node n = parse("\n\n var a = {a:0\n,b :1};")
      .getFirstChild().getFirstChild().getFirstChild();

  assertEquals(Token.OBJECTLIT, n.getType());
  assertEquals(3, n.getLineno());
  assertEquals(9, n.getCharno());

  n = n.getFirstChild();

  assertEquals(Token.STRING, n.getType());
  assertEquals(3, n.getLineno());
  assertEquals(10, n.getCharno());

  n = n.getNext();

  assertEquals(Token.NUMBER, n.getType());
  assertEquals(3, n.getLineno());
  assertEquals(12, n.getCharno());

  n = n.getNext();

  assertEquals(Token.STRING, n.getType());
  assertEquals(4, n.getLineno());
  assertEquals(1, n.getCharno());

  n = n.getNext();

  assertEquals(Token.NUMBER, n.getType());
  assertEquals(4, n.getLineno());
  assertEquals(4, n.getCharno());
}
 
Example 16
Project: feedlack   File: Normalize.java   View Source Code Vote up 5 votes
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  switch (n.getType()) {
    case Token.WHILE:
      if (CONVERT_WHILE_TO_FOR) {
        Node expr = n.getFirstChild();
        n.setType(Token.FOR);
        n.addChildBefore(new Node(Token.EMPTY), expr);
        n.addChildAfter(new Node(Token.EMPTY), expr);
        reportCodeChange("WHILE node");
      }
      break;
  }
}
 
Example 17
Project: feedlack   File: RenameProperties.java   View Source Code Vote up 4 votes
/** {@inheritDoc} */
public void visit(NodeTraversal t, Node n, Node parent) {
  switch (n.getType()) {
    case Token.GETPROP:
      Node propNode = n.getFirstChild().getNext();
      if (propNode.getType() == Token.STRING) {
        maybeMarkCandidate(propNode, t);
      }
      break;
    case Token.OBJECTLIT:
      // The children of an OBJECTLIT node are alternating key/value pairs.
      // We skip the values.
      for (Node key = n.getFirstChild(); key != null;
           key = key.getNext().getNext()) {
        // We only want keys that are strings (not numbers), and only keys
        // that were unquoted.
        if (key.getType() == Token.STRING) {
          if (!key.isQuotedString()) {
            maybeMarkCandidate(key, t);
          } else {
            // Ensure that we never rename some other property in a way
            // that could conflict with this quoted key.
            quotedNames.add(key.getString());
          }
        }
      }
      break;
    case Token.GETELEM:
      // If this is a quoted property access (e.g. x['myprop']), we need to
      // ensure that we never rename some other property in a way that
      // could conflict with this quoted name.
      Node child = n.getLastChild();
      if (child != null && child.getType() == Token.STRING) {
        quotedNames.add(child.getString());
      }
      break;
    case Token.CALL:
      // We replace a JSCompiler_renameProperty function call with a string
      // containing the renamed property.
      Node fnName = n.getFirstChild();
      if (fnName.getType() == Token.NAME &&
          RENAME_PROPERTY_FUNCTION_NAME.equals(fnName.getString())) {
        callNodeToParentMap.put(n, parent);
        countCallCandidates(t, n);
      }
      break;
    case Token.FUNCTION:
      // We eliminate any stub implementations of JSCompiler_renameProperty
      // that we encounter.
      if (NodeUtil.isFunctionDeclaration(n)) {
        String name = n.getFirstChild().getString();
        if (RENAME_PROPERTY_FUNCTION_NAME.equals(name)) {
          if (NodeUtil.isExpressionNode(parent)) {
            parent.detachFromParent();
          } else {
            parent.removeChild(n);
          }
          compiler.reportCodeChange();
        }
      } else if (parent.getType() == Token.NAME &&
                 RENAME_PROPERTY_FUNCTION_NAME.equals(parent.getString())) {
        Node varNode = parent.getParent();
        if (varNode.getType() == Token.VAR) {
          varNode.removeChild(parent);
          if (!varNode.hasChildren()) {
            varNode.detachFromParent();
          }
          compiler.reportCodeChange();
        }
      }
      break;
  }
}
 
Example 18
Project: feedlack   File: AliasStrings.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.getType() == Token.STRING &&
      parent.getType() != Token.GETPROP &&
      parent.getType() != Token.REGEXP &&
      !NodeUtil.isObjectLitKey(n, parent)) {

    String str = n.getString();

    // "undefined" is special-cased, since it needs to be used when JS code
    // is unloading and therefore variable references aren't available.
    // This is because of a bug in FireFox.
    if ("undefined".equals(str)) {
      return;
    }

    if (blacklist != null && blacklist.reset(str).find()) {
      return;
    }

    if (aliasableStrings == null || aliasableStrings.contains(str)) {
      StringOccurrence occurrence = new StringOccurrence(n, parent);
      StringInfo info = getOrCreateStringInfo(str);

      info.occurrences.add(occurrence);
      info.numOccurrences++;

      if (t.inGlobalScope() || isInThrowExpression(n)) {
        info.numOccurrencesInfrequentlyExecuted++;
      }

      if (info.numOccurrences == 1) {

        info.moduleToContainDecl = t.getModule();

        // Take note of the optimal place to insert the var declaration.
        // We'll insert it as the previous sibling of our first ancestor
        // in global scope that has a SCRIPT parent.
        Node prev = n;
        for (Node ancestor : n.getAncestors()) {
          if (ancestor.getType() == Token.SCRIPT) {
            info.parentForNewVarDecl = ancestor;
            info.siblingToInsertVarDeclBefore = prev;
            break;
          }
          prev = ancestor;
        }
      } else {

        // Check whether the current module depends on the module containing
        // the declaration.
        JSModule module = t.getModule();
        if (module != null &&
            info.moduleToContainDecl != null &&
            module != info.moduleToContainDecl &&
            !moduleGraph.dependsOn(module, info.moduleToContainDecl)) {
          // We need to declare this string in the deepest module in the
          // module dependency graph that both of these modules depend on.
          module = moduleGraph.getDeepestCommonDependency(
              module, info.moduleToContainDecl);
          Node varParent = moduleVarParentMap.get(module);
          if (varParent == null) {
            varParent = compiler.getNodeForCodeInsertion(module);
            moduleVarParentMap.put(module, varParent);
          }
          info.moduleToContainDecl = module;
          info.parentForNewVarDecl = varParent;
          info.siblingToInsertVarDeclBefore = varParent.getFirstChild();
        }
      }
    }
  }
}
 
Example 19
Project: feedlack   File: NodeNameExtractor.java   View Source Code Vote up 4 votes
/**
 * Returns a qualified name of the specified node. Dots and brackets
 * are changed to the delimiter passed in when constructing the
 * NodeNameExtractor object.  We also replace ".prototype" with the
 * delimiter to keep names short, while still differentiating them
 * from static properties.  (Prototype properties will end up
 * looking like "a$b$$c" if this.delimiter = '$'.)
 */
String getName(Node node) {
  switch (node.getType()) {
    case Token.FUNCTION:
      Node functionNameNode = node.getFirstChild();
      return functionNameNode.getString();
    case Token.GETPROP:
      Node lhsOfDot = node.getFirstChild();
      Node rhsOfDot = lhsOfDot.getNext();
      String lhsOfDotName = getName(lhsOfDot);
      String rhsOfDotName = getName(rhsOfDot);
      if ("prototype".equals(rhsOfDotName)) {
        return lhsOfDotName + delimiter;
      } else {
        return lhsOfDotName + delimiter + rhsOfDotName;
      }
    case Token.GETELEM:
      Node outsideBrackets = node.getFirstChild();
      Node insideBrackets = outsideBrackets.getNext();
      String nameOutsideBrackets = getName(outsideBrackets);
      String nameInsideBrackets = getName(insideBrackets);
      if ("prototype".equals(nameInsideBrackets)) {
        return nameOutsideBrackets + delimiter;
      } else {
        return nameOutsideBrackets + delimiter + nameInsideBrackets;
      }
    case Token.NAME:
      return node.getString();
    case Token.STRING:
      return TokenStream.isJSIdentifier(node.getString()) ?
          node.getString() : ("__" + nextUniqueInt++);
    case Token.NUMBER:
      return NodeUtil.getStringValue(node);
    case Token.THIS:
      return "this";
    case Token.CALL:
      return getName(node.getFirstChild());
    default:
      StringBuilder sb = new StringBuilder();
      for (Node child = node.getFirstChild(); child != null;
           child = child.getNext()) {
        if (sb.length() > 0) {
          sb.append(delimiter);
        }
        sb.append(getName(child));
      }
      return sb.toString();
  }
}
 
Example 20
Project: feedlack   File: GlobalNamespace.java   View Source Code Vote up 4 votes
/**
 * Determines whether the result of a hook (x?y:z) or boolean expression
 * (x||y) or (x&&y) is assigned to a specific global name.
 *
 * @param t The traversal
 * @param parent The parent of the current node in the traversal. This node
 *     should already be known to be a HOOK, AND, or OR node.
 * @param name A name that is already known to be global in the current
 *     scope (e.g. "a" or "a.b.c.d")
 * @return The expression's get type, either {@link Ref.Type#DIRECT_GET} or
 *     {@link Ref.Type#ALIASING_GET}
 */
Ref.Type determineGetTypeForHookOrBooleanExpr(
    NodeTraversal t, Node parent, String name) {
  Node prev = parent;
  for (Node anc : parent.getAncestors()) {
    switch (anc.getType()) {
      case Token.EXPR_RESULT:
      case Token.VAR:
      case Token.IF:
      case Token.WHILE:
      case Token.FOR:
      case Token.TYPEOF:
      case Token.VOID:
      case Token.NOT:
      case Token.BITNOT:
      case Token.POS:
      case Token.NEG:
        return Ref.Type.DIRECT_GET;
      case Token.HOOK:
        if (anc.getFirstChild() == prev) {
          return Ref.Type.DIRECT_GET;
        }
        break;
      case Token.ASSIGN:
        if (!name.equals(anc.getFirstChild().getQualifiedName())) {
          return Ref.Type.ALIASING_GET;
        }
        break;
      case Token.NAME:  // a variable declaration
        if (!name.equals(anc.getString())) {
          return Ref.Type.ALIASING_GET;
        }
        break;
      case Token.CALL:
        if (anc.getFirstChild() != prev) {
          return Ref.Type.ALIASING_GET;
        }
        break;
    }
    prev = anc;
  }
  return Ref.Type.ALIASING_GET;
}