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

The following examples show how to use com.google.javascript.rhino.Node#isVar() . 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_40_NameAnalyzer_t.java    From coming with MIT License 6 votes vote down vote up
private void addSimplifiedExpression(Node n, Node parent) {
  if (parent.isVar()) {
    Node value = n.getFirstChild();
    if (value != null) {
      addSimplifiedChildren(value);
    }
  } else if (n.isAssign() &&
      (parent.isExprResult() ||
       parent.isFor() ||
       parent.isReturn())) {
    for (Node child : n.children()) {
      addSimplifiedChildren(child);
    }
  } else if (n.isCall() &&
             parent.isExprResult()) {
    addSimplifiedChildren(n);
  } else {
    addAllChildren(n);
  }
}
 
Example 2
Source File: Closure_114_NameAnalyzer_t.java    From coming with MIT License 6 votes vote down vote up
private void addSimplifiedExpression(Node n, Node parent) {
  if (parent.isVar()) {
    Node value = n.getFirstChild();
    if (value != null) {
      addSimplifiedChildren(value);
    }
  } else if (n.isAssign() &&
      (parent.isExprResult() ||
       parent.isFor() ||
       parent.isReturn())) {
    for (Node child : n.children()) {
      addSimplifiedChildren(child);
    }
  } else if (n.isCall() &&
             parent.isExprResult()) {
    addSimplifiedChildren(n);
  } else {
    addAllChildren(n);
  }
}
 
Example 3
Source File: Cardumen_0092_s.java    From coming with MIT License 6 votes vote down vote up
private void addSimplifiedExpression(Node n, Node parent) {
  if (parent.isVar()) {
    Node value = n.getFirstChild();
    if (value != null) {
      addSimplifiedChildren(value);
    }
  } else if (n.isAssign() &&
      (parent.isExprResult() ||
       parent.isFor() ||
       parent.isReturn())) {
    for (Node child : n.children()) {
      addSimplifiedChildren(child);
    }
  } else if (n.isCall() &&
             parent.isExprResult()) {
    addSimplifiedChildren(n);
  } else {
    addAllChildren(n);
  }
}
 
Example 4
Source File: Cardumen_0014_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 5
Source File: Closure_114_NameAnalyzer_s.java    From coming with MIT License 6 votes vote down vote up
private void addSimplifiedExpression(Node n, Node parent) {
  if (parent.isVar()) {
    Node value = n.getFirstChild();
    if (value != null) {
      addSimplifiedChildren(value);
    }
  } else if (n.isAssign() &&
      (parent.isExprResult() ||
       parent.isFor() ||
       parent.isReturn())) {
    for (Node child : n.children()) {
      addSimplifiedChildren(child);
    }
  } else if (n.isCall() &&
             parent.isExprResult()) {
    addSimplifiedChildren(n);
  } else {
    addAllChildren(n);
  }
}
 
Example 6
Source File: StripCode.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets whether a CALL node triggers statement removal, based on the name
 * of the object whose method is being called, or the name of the method.
 * Checks whether the name begins with a strip type, ends with a field name
 * that's a strip name, or belongs to the set of global class-defining
 * functions (e.g. goog.inherits).
 *
 * @param t The traversal
 * @param n A CALL node
 * @return Whether the node triggers statement removal
 */
boolean isMethodOrCtorCallThatTriggersRemoval(
    NodeTraversal t, Node n, Node parent) {
  // CALL/NEW
  //   GETPROP (function)         <-- we're interested in this, the function
  //     GETPROP (callee object)  <-- or the object on which it is called
  //       ...
  //       STRING (field name)
  //     STRING (method name)
  //   ... (arguments)

  Node function = n.getFirstChild();
  if (function == null || !function.isGetProp()) {
    // We are only interested in calls on object references that are
    // properties. We don't need to eliminate method calls on variables
    // that are getting removed, since that's already done by the code
    // that removes all references to those variables.
    return false;
  }

  if (parent != null && parent.isName()) {
    Node gramps = parent.getParent();
    if (gramps != null && gramps.isVar()) {
      // The call's return value is being used to initialize a newly
      // declared variable. We should leave the call intact for now.
      // That way, when the traversal reaches the variable declaration,
      // we'll recognize that the variable and all references to it need
      // to be eliminated.
      return false;
    }
  }

  Node callee = function.getFirstChild();
  return nameEndsWithFieldNameToStrip(callee) ||
      nameEndsWithFieldNameToStrip(function) ||
      qualifiedNameBeginsWithStripType(function) ||
      actsOnStripType(t, n);
}
 
Example 7
Source File: Cardumen_0014_t.java    From coming with MIT License 5 votes vote down vote up
/** Find the best JSDoc for the given node. */
static JSDocInfo getBestJSDocInfo(Node n) {
  JSDocInfo info = n.getJSDocInfo();
  if (info == null) {
    Node parent = n.getParent();
    if (parent == null) {
      return null;
    }

    if (parent.isName()) {
      return getBestJSDocInfo(parent);
    } else if (parent.isAssign()) {
      return parent.getJSDocInfo();
    } else if (isObjectLitKey(parent, parent.getParent())) {
      return parent.getJSDocInfo();
    } else if (parent.isFunction()) {
      return parent.getJSDocInfo();
    } else if (parent.isVar() && parent.hasOneChild()) {
      return parent.getJSDocInfo();
    } else if ((parent.isHook() && parent.getFirstChild() != n) ||
               parent.isOr() ||
               parent.isAnd() ||
               (parent.isComma() && parent.getFirstChild() != n)) {
      return getBestJSDocInfo(parent);
    }
  }
  return info;
}
 
Example 8
Source File: NodeUtil.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Find the best JSDoc for the given node. */
static JSDocInfo getBestJSDocInfo(Node n) {
  JSDocInfo info = n.getJSDocInfo();
  if (info == null) {
    Node parent = n.getParent();
    if (parent == null) {
      return null;
    }

    if (parent.isName()) {
      return getBestJSDocInfo(parent);
    } else if (parent.isAssign()) {
      return parent.getJSDocInfo();
    } else if (isObjectLitKey(parent, parent.getParent())) {
      return parent.getJSDocInfo();
    } else if (parent.isFunction()) {
      return parent.getJSDocInfo();
    } else if (parent.isVar() && parent.hasOneChild()) {
      return parent.getJSDocInfo();
    } else if ((parent.isHook() && parent.getFirstChild() != n) ||
               parent.isOr() ||
               parent.isAnd() ||
               (parent.isComma() && parent.getFirstChild() != n)) {
      return getBestJSDocInfo(parent);
    } else if (parent.isCast()) {
      return parent.getJSDocInfo();
    }
  }
  return info;
}
 
Example 9
Source File: AstValidator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void validateVarOrAssignmentTarget(Node n) {
  if (n.isVar()) {
    // Only one NAME can be declared for FOR-IN expressions.
    this.validateChildCount(n, 1);
    validateVar(n);
  } else {
    validateAssignmentTarget(n);
  }
}
 
Example 10
Source File: Cardumen_0014_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 11
Source File: jMutRepair_003_t.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 12
Source File: Closure_117_TypeValidator_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Expect that the given variable has not been declared with a type.
 *
 * @param sourceName The name of the source file we're in.
 * @param n The node where warnings should point to.
 * @param parent The parent of {@code n}.
 * @param var The variable that we're checking.
 * @param variableName The name of the variable.
 * @param newType The type being applied to the variable. Mostly just here
 *     for the benefit of the warning.
 * @return The variable we end up with. Most of the time, this will just
 *     be {@code var}, but in some rare cases we will need to declare
 *     a new var with new source info.
 */
Var expectUndeclaredVariable(String sourceName, CompilerInput input,
    Node n, Node parent, Var var, String variableName, JSType newType) {
  Var newVar = var;
  boolean allowDupe = false;
  if (n.isGetProp() ||
      NodeUtil.isObjectLitKey(n)) {
    JSDocInfo info = n.getJSDocInfo();
    if (info == null) {
      info = parent.getJSDocInfo();
    }
    allowDupe =
        info != null && info.getSuppressions().contains("duplicate");
  }

  JSType varType = var.getType();

  // Only report duplicate declarations that have types. Other duplicates
  // will be reported by the syntactic scope creator later in the
  // compilation process.
  if (varType != null &&
      varType != typeRegistry.getNativeType(UNKNOWN_TYPE) &&
      newType != null &&
      newType != typeRegistry.getNativeType(UNKNOWN_TYPE)) {
    // If there are two typed declarations of the same variable, that
    // is an error and the second declaration is ignored, except in the
    // case of native types. A null input type means that the declaration
    // was made in TypedScopeCreator#createInitialScope and is a
    // native type. We should redeclare it at the new input site.
    if (var.input == null) {
      Scope s = var.getScope();
      s.undeclare(var);
      newVar = s.declare(variableName, n, varType, input, false);

      n.setJSType(varType);
      if (parent.isVar()) {
        if (n.getFirstChild() != null) {
          n.getFirstChild().setJSType(varType);
        }
      } else {
        Preconditions.checkState(parent.isFunction());
        parent.setJSType(varType);
      }
    } else {
      // Always warn about duplicates if the overridden type does not
      // match the original type.
      //
      // If the types match, suppress the warning iff there was a @suppress
      // tag, or if the original declaration was a stub.
      if (!(allowDupe ||
            var.getParentNode().isExprResult()) ||
          !newType.isEquivalentTo(varType)) {
        report(JSError.make(sourceName, n, DUP_VAR_DECLARATION,
            variableName, newType.toString(), var.getInputName(),
            String.valueOf(var.nameNode.getLineno()),
            varType.toString()));
      }
    }
  }

  return newVar;
}
 
Example 13
Source File: Closure_8_CollapseVariableDeclarations_t.java    From coming with MIT License 4 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.isVar()) {
    blacklistStubVars(t, n);
  }

  // Only care about var nodes
  if (!n.isVar() && !canBeRedeclared(n, t.getScope())) return;

  // If we've already looked at this node, skip it
  if (nodesToCollapse.contains(n)) return;

  // Adjacent VAR children of an IF node are the if and else parts and can't
  // be collapsed
  if (parent.isIf()) return;

  Node varNode = n;

  boolean hasVar = n.isVar();

  // Find variable declarations that follow this one (if any)
  n = n.getNext();

  boolean hasNodesToCollapse = false;

  while (n != null &&
      (n.isVar() || canBeRedeclared(n, t.getScope()))) {

    if (n.isVar()) {
      blacklistStubVars(t, n);
      hasVar = true;
    }

    nodesToCollapse.add(n);
    hasNodesToCollapse = true;

    n = n.getNext();
  }

  if (hasNodesToCollapse && hasVar) {
    nodesToCollapse.add(varNode);
    collapses.add(new Collapse(varNode, n, parent));
  }
}
 
Example 14
Source File: Cardumen_00203_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Removes any vars in the scope that were not referenced. Removes any
 * assignments to those variables as well.
 */
private void removeUnreferencedVars() {
  CodingConvention convention = codingConvention;

  for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
    Var var = it.next();

    // Remove calls to inheritance-defining functions where the unreferenced
    // class is the subclass.
    for (Node exprCallNode : inheritsCalls.get(var)) {
      NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
      compiler.reportCodeChange();
    }

    // Regardless of what happens to the original declaration,
    // we need to remove all assigns, because they may contain references
    // to other unreferenced variables.
    removeAllAssigns(var);

    compiler.addToDebugLog("Unreferenced var: " + var.name);
    Node nameNode = var.nameNode;
    Node toRemove = nameNode.getParent();
    Node parent = toRemove.getParent();

    Preconditions.checkState(
        toRemove.isVar() ||
        toRemove.isFunction() ||
        toRemove.isParamList() &&
        parent.isFunction(),
        "We should only declare vars and functions and function args");

    if (toRemove.isParamList() &&
        parent.isFunction()) {
      // Don't remove function arguments here. That's a special case
      // that's taken care of in removeUnreferencedFunctionArgs.
    } else if (NodeUtil.isFunctionExpression(toRemove)) {
      if (!preserveFunctionExpressionNames) {
        toRemove.getFirstChild().setString("");
        compiler.reportCodeChange();
      }
      // Don't remove bleeding functions.
    } else if (parent != null &&
        parent.isFor() &&
        parent.getChildCount() < 4) {
      // foreach iterations have 3 children. Leave them alone.
    } else if (toRemove.isVar() &&
        nameNode.hasChildren() &&
        NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
      // If this is a single var declaration, we can at least remove the
      // declaration itself and just leave the value, e.g.,
      // var a = foo(); => foo();
      if (toRemove.getChildCount() == 1) {
        parent.replaceChild(toRemove,
            IR.exprResult(nameNode.removeFirstChild()));
        compiler.reportCodeChange();
      }
    } else if (toRemove.isVar() &&
        toRemove.getChildCount() > 1) {
      // For var declarations with multiple names (i.e. var a, b, c),
      // only remove the unreferenced name
      toRemove.removeChild(nameNode);
      compiler.reportCodeChange();
    } else if (parent != null) {
      NodeUtil.removeChild(parent, toRemove);
      compiler.reportCodeChange();
    }
  }
}
 
Example 15
Source File: Closure_34_CodeGenerator_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Adds a block or expression, substituting a VOID with an empty statement.
 * This is used for "for (...);" and "if (...);" type statements.
 *
 * @param n The node to print.
 * @param context The context to determine how the node should be printed.
 */
private void addNonEmptyStatement(
    Node n, Context context, boolean allowNonBlockChild) {
  Node nodeToProcess = n;

  if (!allowNonBlockChild && !n.isBlock()) {
    throw new Error("Missing BLOCK child.");
  }

  // Strip unneeded blocks, that is blocks with <2 children unless
  // the CodePrinter specifically wants to keep them.
  if (n.isBlock()) {
    int count = getNonEmptyChildCount(n, 2);
    if (count == 0) {
      if (cc.shouldPreserveExtraBlocks()) {
        cc.beginBlock();
        cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
      } else {
        cc.endStatement(true);
      }
      return;
    }

    if (count == 1) {
      // Hack around a couple of browser bugs:
      //   Safari needs a block around function declarations.
      //   IE6/7 needs a block around DOs.
      Node firstAndOnlyChild = getFirstNonEmptyChild(n);
      boolean alwaysWrapInBlock = cc.shouldPreserveExtraBlocks();
      if (alwaysWrapInBlock || isOneExactlyFunctionOrDo(firstAndOnlyChild)) {
        cc.beginBlock();
        add(firstAndOnlyChild, Context.STATEMENT);
        cc.maybeLineBreak();
        cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
        return;
      } else {
        // Continue with the only child.
        nodeToProcess = firstAndOnlyChild;
      }
    }

    if (count > 1) {
      context = Context.PRESERVE_BLOCK;
    }
  }

  if (nodeToProcess.isEmpty()) {
    cc.endStatement(true);
  } else {
    add(nodeToProcess, context);

    // VAR doesn't include ';' since it gets used in expressions - so any
    // VAR in a statement context needs a call to endStatement() here.
    if (nodeToProcess.isVar()) {
      cc.endStatement();
    }
  }
}
 
Example 16
Source File: MarkNoSideEffectCalls.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visit(NodeTraversal traversal, Node node, Node parent) {
  if (!inExterns && hasNoSideEffectsAnnotation(node)) {
    traversal.report(node, INVALID_NO_SIDE_EFFECT_ANNOTATION);
  }

  if (node.isGetProp()) {
    if (parent.isExprResult() &&
        hasNoSideEffectsAnnotation(node)) {
      noSideEffectFunctionNames.add(node);
    }
  } else if (node.isFunction()) {

    // The annotation may attached to the function node, the
    // variable declaration or assignment expression.
    boolean hasAnnotation = hasNoSideEffectsAnnotation(node);
    List<Node> nameNodes = Lists.newArrayList();
    nameNodes.add(node.getFirstChild());

    Node nameNode = null;

    if (parent.isName()) {
      Node gramp = parent.getParent();
      if (gramp.isVar() &&
          gramp.hasOneChild() &&
          hasNoSideEffectsAnnotation(gramp)) {
        hasAnnotation = true;
      }

      nameNodes.add(parent);
    } else if (parent.isAssign()) {
      if (hasNoSideEffectsAnnotation(parent)) {
        hasAnnotation = true;
      }

      nameNodes.add(parent.getFirstChild());
    }

    if (hasAnnotation) {
      noSideEffectFunctionNames.addAll(nameNodes);
    }
  }
}
 
Example 17
Source File: Cardumen_00149_t.java    From coming with MIT License 4 votes vote down vote up
@Override
public boolean apply(Node n) {
  return isFunctionDeclaration(n) || n.isVar();
}
 
Example 18
Source File: jMutRepair_003_t.java    From coming with MIT License 4 votes vote down vote up
@Override
public boolean apply(Node n) {
  return isFunctionDeclaration(n) || n.isVar();
}
 
Example 19
Source File: jKali_003_s.java    From coming with MIT License 4 votes vote down vote up
@Override
public boolean apply(Node n) {
  return isFunctionDeclaration(n) || n.isVar();
}
 
Example 20
Source File: jMutRepair_003_t.java    From coming with MIT License 2 votes vote down vote up
/**
 * Determines whether this node is strictly on the left hand side of an assign
 * or var initialization. Notably, this does not include all L-values, only
 * statements where the node is used only as an L-value.
 *
 * @param n The node
 * @param parent Parent of the node
 * @return True if n is the left hand of an assign
 */
static boolean isVarOrSimpleAssignLhs(Node n, Node parent) {
  return (parent.isAssign() && parent.getFirstChild() == n) ||
         parent.isVar();
}