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

The following examples show how to use com.google.javascript.rhino.Node#getFirstChild() . 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: Cardumen_0087_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Determines whether this node is used as an L-value. Notice that sometimes
 * names are used as both L-values and R-values.
 *
 * We treat "var x;" as a pseudo-L-value, which kind of makes sense if you
 * treat it as "assignment to 'undefined' at the top of the scope". But if
 * we're honest with ourselves, it doesn't make sense, and we only do this
 * because it makes sense to treat this as syntactically similar to
 * "var x = 0;".
 *
 * @param n The node
 * @return True if n is an L-value.
 */
public static boolean isLValue(Node n) {
  Preconditions.checkArgument(n.isName() || n.isGetProp() ||
      n.isGetElem());
  Node parent = n.getParent();
  if (parent == null) {
    return false;
  }
  return (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n)
      || (NodeUtil.isForIn(parent) && parent.getFirstChild() == n)
      || parent.isVar()
      || (parent.isFunction() && parent.getFirstChild() == n)
      || parent.isDec()
      || parent.isInc()
      || parent.isParamList()
      || parent.isCatch();
}
 
Example 2
Source File: Closure_95_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 3
Source File: Cardumen_0087_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * @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 4
Source File: NameAnalyzer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Merge a list of nodes into a single expression.  The value of the
 * new expression is determined by the last expression in the list.
 */
private Node collapseReplacements(List<Node> replacements) {
  Node expr = null;
  for (Node rep : replacements) {
    if (rep.isExprResult()) {
      rep = rep.getFirstChild();
      rep.detachFromParent();
    }

    if (expr == null) {
      expr = rep;
    } else {
      expr = IR.comma(expr, rep);
    }
  }

  return expr;
}
 
Example 5
Source File: Closure_132_PeepholeSubstituteAlternateSyntax_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return Whether the node is a block with a single statement that is
 *     an return.
 */
private boolean isReturnExpressBlock(Node n) {
  if (n.isBlock()) {
    if (n.hasOneChild()) {
      Node first = n.getFirstChild();
      if (first.isReturn()) {
        return first.hasOneChild();
      }
    }
  }

  return false;
}
 
Example 6
Source File: Nopol2017_0029_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Visits a RETURN node.
 *
 * @param t The node traversal object that supplies context, such as the
 * scope chain to use in name lookups as well as error reporting.
 * @param n The node being visited.
 */
private void visitReturn(NodeTraversal t, Node n) {
  JSType jsType = getJSType(t.getEnclosingFunction());

  if (jsType.isFunctionType()) {
    FunctionType functionType = jsType.toMaybeFunctionType();

    JSType returnType = functionType.getReturnType();

    // if no return type is specified, undefined must be returned
    // (it's a void function)
    if (returnType == null) {
      returnType = getNativeType(VOID_TYPE);
    }

    // fetching the returned value's type
    Node valueNode = n.getFirstChild();
    JSType actualReturnType;
    if (valueNode == null) {
      actualReturnType = getNativeType(VOID_TYPE);
      valueNode = n;
    } else {
      actualReturnType = getJSType(valueNode);
    }

    // verifying
    validator.expectCanAssignTo(t, valueNode, actualReturnType, returnType,
        "inconsistent return type");
  }
}
 
Example 7
Source File: Closure_34_CodeGenerator_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param maxCount The maximum number of children to look for.
 * @return The number of children of this node that are non empty up to
 * maxCount.
 */
private static int getNonEmptyChildCount(Node n, int maxCount) {
  int i = 0;
  Node c = n.getFirstChild();
  for (; c != null && i < maxCount; c = c.getNext()) {
    if (c.isBlock()) {
      i += getNonEmptyChildCount(c, maxCount-i);
    } else if (!c.isEmpty()) {
      i++;
    }
  }
  return i;
}
 
Example 8
Source File: Closure_61_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * A post-order traversal, calling Vistor.visit for each child matching
 * the predicate.
 */
static void visitPostOrder(Node node,
                   Visitor vistor,
                   Predicate<Node> traverseChildrenPred) {
  if (traverseChildrenPred.apply(node)) {
    for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
      visitPostOrder(c, vistor, traverseChildrenPred);
    }
  }

  vistor.visit(node);
}
 
Example 9
Source File: Cardumen_00200_t.java    From coming with MIT License 5 votes vote down vote up
/** Get the owner of the given l-value node. */
static Node getBestLValueOwner(@Nullable Node lValue) {
  if (lValue == null || lValue.getParent() == null) {
    return null;
  }
  if (isObjectLitKey(lValue, lValue.getParent())) {
    return getBestLValue(lValue.getParent());
  } else if (isGet(lValue)) {
    return lValue.getFirstChild();
  }

  return null;
}
 
Example 10
Source File: Cardumen_00200_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return The class name part of a qualified prototype name.
 */
static Node getPrototypeClassName(Node qName) {
  Node cur = qName;
  while (cur.isGetProp()) {
    if (cur.getLastChild().getString().equals("prototype")) {
      return cur.getFirstChild();
    } else {
      cur = cur.getFirstChild();
    }
  }
  return null;
}
 
Example 11
Source File: Cardumen_00151_t.java    From coming with MIT License 5 votes vote down vote up
@Override
public void keepSimplifiedShortCircuitExpression(Node original) {
  Node condition = original.getFirstChild();
  Node thenBranch = condition.getNext();
  addAllChildren(condition);
  addSimplifiedChildren(thenBranch);
}
 
Example 12
Source File: Closure_78_PeepholeFoldConstants_t.java    From coming with MIT License 5 votes vote down vote up
private Node tryReduceVoid(Node n) {
  Node child = n.getFirstChild();
  if (child.getType() != Token.NUMBER || child.getDouble() != 0.0) {
    if (!mayHaveSideEffects(n)) {
      n.replaceChild(child, Node.newNumber(0));
      reportCodeChange();
    }
  }
  return n;
}
 
Example 13
Source File: Closure_87_PeepholeSubstituteAlternateSyntax_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return Whether the node is a block with a single statement that is
 *     a VAR declaration of a single variable.
 */
private boolean isVarBlock(Node n) {
  if (n.getType() == Token.BLOCK) {
    if (n.hasOneChild()) {
      Node first = n.getFirstChild();
      if (first.getType() == Token.VAR) {
        return first.hasOneChild();
      }
    }
  }

  return false;
}
 
Example 14
Source File: Closure_10_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param n The node to inspect.
 * @return If the node, is a FOR, WHILE, or DO, it returns the node for
 * the code BLOCK, null otherwise.
 */
static Node getLoopCodeBlock(Node n) {
  switch (n.getType()) {
    case Token.FOR:
    case Token.WHILE:
      return n.getLastChild();
    case Token.DO:
      return n.getFirstChild();
    default:
      return null;
  }
}
 
Example 15
Source File: jKali_0034_s.java    From coming with MIT License 5 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.isCall()) {
    Node target = n.getFirstChild();
    // TODO(johnlenz): add this to the coding convention
    // so we can remove goog.reflect.sinkValue as well.
    if (target.isName() && target.getString().equals(PROTECTOR_FN)) {
      Node expr = n.getLastChild();
      n.detachChildren();
      parent.replaceChild(n, expr);
    }
  }
}
 
Example 16
Source File: NodeUtilTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testIsFunctionExpression1() {
  Node root = parse("(function foo() {})");
  Node statementNode = root.getFirstChild();
  assertTrue(statementNode.isExprResult());
  Node functionNode = statementNode.getFirstChild();
  assertTrue(functionNode.isFunction());
  assertTrue(NodeUtil.isFunctionExpression(functionNode));
}
 
Example 17
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return The expression node.
 */
private Node getBlockExpression(Node n) {
  Preconditions.checkState(isExpressBlock(n));
  return n.getFirstChild();
}
 
Example 18
Source File: Closure_112_TypeInference_s.java    From coming with MIT License 4 votes vote down vote up
private FlowScope traverseChildren(Node n, FlowScope scope) {
  for (Node el = n.getFirstChild(); el != null; el = el.getNext()) {
    scope = traverse(el, scope);
  }
  return scope;
}
 
Example 19
Source File: Nopol2017_0010_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Handles a goog.require call.
 */
private void processRequireCall(NodeTraversal t, Node n, Node parent) {
  Node left = n.getFirstChild();
  Node arg = left.getNext();
  if (verifyLastArgumentIsString(t, left, arg)) {
    String ns = arg.getString();
    ProvidedName provided = providedNames.get(ns);
    if (provided == null || !provided.isExplicitlyProvided()) {
      unrecognizedRequires.add(
          new UnrecognizedRequire(n, ns, t.getSourceName()));
    } else {
      JSModule providedModule = provided.explicitModule;

      // This must be non-null, because there was an explicit provide.
      Preconditions.checkNotNull(providedModule);

      JSModule module = t.getModule();
      if (moduleGraph != null &&
          module != providedModule &&
          !moduleGraph.dependsOn(module, providedModule)) {
        compiler.report(
            t.makeError(n, XMODULE_REQUIRE_ERROR, ns,
                providedModule.getName(),
                module.getName()));
      }
    }

    maybeAddToSymbolTable(left);
    maybeAddStringNodeToSymbolTable(arg);

    // Requires should be removed before further processing.
    // Some clients run closure pass multiple times, first with
    // the checks for broken requires turned off. In these cases, we
    // allow broken requires to be preserved by the first run to
    // let them be caught in the subsequent run.
    if (provided != null) {
      parent.detachFromParent();
      compiler.reportCodeChange();
    }
  }
}
 
Example 20
Source File: Nopol2017_0051_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * This function unifies the type checking involved in the core binary
 * operators and the corresponding assignment operators.  The representation
 * used internally is such that common code can handle both kinds of
 * operators easily.
 *
 * @param op The operator.
 * @param t The traversal object, needed to report errors.
 * @param n The node being checked.
 */
private void visitBinaryOperator(int op, NodeTraversal t, Node n) {
  Node left = n.getFirstChild();
  JSType leftType = getJSType(left);
  Node right = n.getLastChild();
  JSType rightType = getJSType(right);
  switch (op) {
    case Token.ASSIGN_LSH:
    case Token.ASSIGN_RSH:
    case Token.LSH:
    case Token.RSH:
    case Token.ASSIGN_URSH:
    case Token.URSH:
      if (!leftType.matchesInt32Context()) {
        report(t, left, BIT_OPERATION,
                 NodeUtil.opToStr(n.getType()), leftType.toString());
      }
      if (!rightType.matchesUint32Context()) {
        report(t, right, BIT_OPERATION,
                 NodeUtil.opToStr(n.getType()), rightType.toString());
      }
      break;

    case Token.ASSIGN_DIV:
    case Token.ASSIGN_MOD:
    case Token.ASSIGN_MUL:
    case Token.ASSIGN_SUB:
    case Token.DIV:
    case Token.MOD:
    case Token.MUL:
    case Token.SUB:
      validator.expectNumber(t, left, leftType, "left operand");
      validator.expectNumber(t, right, rightType, "right operand");
      break;

    case Token.ASSIGN_BITAND:
    case Token.ASSIGN_BITXOR:
    case Token.ASSIGN_BITOR:
    case Token.BITAND:
    case Token.BITXOR:
    case Token.BITOR:
      validator.expectBitwiseable(t, left, leftType,
          "bad left operand to bitwise operator");
      validator.expectBitwiseable(t, right, rightType,
          "bad right operand to bitwise operator");
      break;

    case Token.ASSIGN_ADD:
    case Token.ADD:
      break;

    default:
      report(t, n, UNEXPECTED_TOKEN, Node.tokenToName(op));
  }
  ensureTyped(t, n);
}