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

The following examples show how to use com.google.javascript.rhino.Node#getParent() . 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: Nopol2017_0027_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Returns the type specified in a JSDoc annotation near a GETPROP or NAME.
 *
 * Extracts type information from either the {@code @type} tag or from
 * the {@code @return} and {@code @param} tags.
 */
private JSType getDeclaredTypeInAnnotation(String sourceName,
    Node node, JSDocInfo info) {
  JSType jsType = null;
  Node objNode =
      node.isGetProp() ? node.getFirstChild() :
      NodeUtil.isObjectLitKey(node, node.getParent()) ? node.getParent() :
      null;
  if (info != null) {
    if (info.hasType()) {
      jsType = info.getType().evaluate(scope, typeRegistry);
    } else if (FunctionTypeBuilder.isFunctionTypeDeclaration(info)) {
      String fnName = node.getQualifiedName();
      jsType = createFunctionTypeFromNodes(
          null, fnName, info, node);
    }
  }
  return jsType;
}
 
Example 2
Source File: NodeUtil.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Find the l-value that the given r-value is being assigned to. */
static Node getBestLValue(Node n) {
  Node parent = n.getParent();
  boolean isFunctionDeclaration = isFunctionDeclaration(n);
  if (isFunctionDeclaration) {
    return n.getFirstChild();
  } else if (parent.isName()) {
    return parent;
  } else if (parent.isAssign()) {
    return parent.getFirstChild();
  } else if (isObjectLitKey(parent, parent.getParent())) {
    return parent;
  } else if (
      (parent.isHook() && parent.getFirstChild() != n) ||
      parent.isOr() ||
      parent.isAnd() ||
      (parent.isComma() && parent.getFirstChild() != n)) {
    return getBestLValue(parent);
  } else if (parent.isCast()) {
    return getBestLValue(parent);
  }
  return null;
}
 
Example 3
Source File: Closure_75_NodeUtil_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets a Node at the top of the current scope where we can add new var
 * declarations as children.
 */
private static Node getAddingRoot(Node n) {
  Node addingRoot = null;
  Node ancestor = n;
  while (null != (ancestor = ancestor.getParent())) {
    int type = ancestor.getType();
    if (type == Token.SCRIPT) {
      addingRoot = ancestor;
      break;
    } else if (type == Token.FUNCTION) {
      addingRoot = ancestor.getLastChild();
      break;
    }
  }

  // make sure that the adding root looks ok
  Preconditions.checkState(addingRoot.getType() == Token.BLOCK ||
      addingRoot.getType() == Token.SCRIPT);
  Preconditions.checkState(addingRoot.getFirstChild() == null ||
      addingRoot.getFirstChild().getType() != Token.SCRIPT);
  return addingRoot;
}
 
Example 4
Source File: Closure_60_NodeUtil_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Get the JSDocInfo for a function.
 */
public static JSDocInfo getFunctionJSDocInfo(Node n) {
  Preconditions.checkState(n.getType() == Token.FUNCTION);
  JSDocInfo fnInfo = n.getJSDocInfo();
  if (fnInfo == null && NodeUtil.isFunctionExpression(n)) {
    // Look for the info on other nodes.
    Node parent = n.getParent();
    if (parent.getType() == Token.ASSIGN) {
      // on ASSIGNs
      fnInfo = parent.getJSDocInfo();
    } else if (parent.getType() == Token.NAME) {
      // on var NAME = function() { ... };
      fnInfo = parent.getParent().getJSDocInfo();
    }
  }
  return fnInfo;
}
 
Example 5
Source File: Closure_61_NodeUtil_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param nameNode A name node
 * @return The JSDocInfo for the name node
 */
static JSDocInfo getInfoForNameNode(Node nameNode) {
  JSDocInfo info = null;
  Node parent = null;
  if (nameNode != null) {
    info = nameNode.getJSDocInfo();
    parent = nameNode.getParent();
  }

  if (info == null && parent != null &&
      ((parent.getType() == Token.VAR && parent.hasOneChild()) ||
        parent.getType() == Token.FUNCTION)) {
    info = parent.getJSDocInfo();
  }
  return info;
}
 
Example 6
Source File: Cardumen_00200_t.java    From coming with MIT License 6 votes vote down vote up
/** Get the name of the given l-value node. */
static String getBestLValueName(@Nullable Node lValue) {
  if (lValue == null || lValue.getParent() == null) {
    return null;
  }
  if (isObjectLitKey(lValue, lValue.getParent())) {
    Node owner = getBestLValue(lValue.getParent());
    if (owner != null) {
      String ownerName = getBestLValueName(owner);
      if (ownerName != null) {
        return ownerName + "." + getObjectLitKeyName(lValue);
      }
    }
    return null;
  }
  return lValue.getQualifiedName();
}
 
Example 7
Source File: Nopol2017_0029_t.java    From coming with MIT License 6 votes vote down vote up
/** Main entry point of this phase for testing code. */
public Scope processForTesting(Node externsRoot, Node jsRoot) {
  Preconditions.checkState(scopeCreator == null);
  Preconditions.checkState(topScope == null);

  Preconditions.checkState(jsRoot.getParent() != null);
  Node externsAndJsRoot = jsRoot.getParent();

  scopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler));
  topScope = scopeCreator.createScope(externsAndJsRoot, null);

  TypeInferencePass inference = new TypeInferencePass(compiler,
      reverseInterpreter, topScope, scopeCreator);

  inference.process(externsRoot, jsRoot);
  process(externsRoot, jsRoot);

  return topScope;
}
 
Example 8
Source File: Cardumen_00149_t.java    From coming with MIT License 6 votes vote down vote up
/** Find the l-value that the given r-value is being assigned to. */
static Node getBestLValue(Node n) {
  Node parent = n.getParent();
  boolean isFunctionDeclaration = isFunctionDeclaration(n);
  if (isFunctionDeclaration) {
    return n.getFirstChild();
  } else if (parent.isName()) {
    return parent;
  } else if (parent.isAssign()) {
    return parent.getFirstChild();
  } else if (isObjectLitKey(parent, parent.getParent())) {
    return parent;
  } else if (
      (parent.isHook() && parent.getFirstChild() != n) ||
      parent.isOr() ||
      parent.isAnd() ||
      (parent.isComma() && parent.getFirstChild() != n)) {
    return getBestLValue(parent);
  }
  return null;
}
 
Example 9
Source File: jMutRepair_003_s.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 10
Source File: Closure_10_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param n The node.
 * @return The source name property on the node or its ancestors.
 */
public static String getSourceName(Node n) {
  String sourceName = null;
  while (sourceName == null && n != null) {
    sourceName = n.getSourceFileName();
    n = n.getParent();
  }
  return sourceName;
}
 
Example 11
Source File: jMutRepair_003_s.java    From coming with MIT License 5 votes vote down vote up
@Override
public boolean apply(Node n) {
  Node parent = n.getParent();
  return n.isBlock()
      || (!n.isFunction() && (parent == null
          || isControlStructure(parent)
          || isStatementBlock(parent)));
}
 
Example 12
Source File: PeepholeRemoveDeadCode.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes DOs that always evaluate to false. This leaves the
 * statements that were in the loop in a BLOCK node.
 * The block will be removed in a later pass, if possible.
 */
Node tryFoldDo(Node n) {
  Preconditions.checkArgument(n.isDo());

  Node cond = NodeUtil.getConditionExpression(n);
  if (NodeUtil.getImpureBooleanValue(cond) != TernaryValue.FALSE) {
    return n;
  }

  // TODO(johnlenz): The do-while can be turned into a label with
  // named breaks and the label optimized away (maybe).
  if (hasBreakOrContinue(n)) {
    return n;
  }

  Preconditions.checkState(
      NodeUtil.isControlStructureCodeBlock(n, n.getFirstChild()));
  Node block = n.removeFirstChild();

  Node parent =  n.getParent();
  parent.replaceChild(n, block);
  if (mayHaveSideEffects(cond)) {
    Node condStatement = IR.exprResult(cond.detachFromParent())
        .srcref(cond);
    parent.addChildAfter(condStatement, block);
  }
  reportCodeChange();

  return n;
}
 
Example 13
Source File: jKali_007_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Remove all references to a parameter if possible otherwise simplify the
 * side-effect free parameters.
 */
private void tryRemoveArgFromCallSites(
    Node function, int argIndex, boolean canModifyAllSites) {
  Definition definition = getFunctionDefinition(function);

  for (UseSite site : defFinder.getUseSites(definition)) {
    if (isModifiableCallSite(site)) {
      Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex);
      if (arg != null) {
        Node argParent = arg.getParent();
        // Even if we can't change the signature in general we can always
        // remove an unused value off the end of the parameter list.
        if (canModifyAllSites
            || (arg.getNext() == null
                && !NodeUtil.mayHaveSideEffects(arg, compiler))) {
          toRemove.add(arg);
        } else {
          // replace the node in the arg with 0
          if (!NodeUtil.mayHaveSideEffects(arg, compiler)
              && (!arg.isNumber() || arg.getDouble() != 0)) {
            toReplaceWithZero.add(arg);
          }
        }
      }
    }
  }
}
 
Example 14
Source File: Closure_69_TypeCheck_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Main entry point for this phase of processing. This follows the pattern for
 * JSCompiler phases.
 *
 * @param externsRoot The root of the externs parse tree.
 * @param jsRoot The root of the input parse tree to be checked.
 */
public void process(Node externsRoot, Node jsRoot) {
  Preconditions.checkNotNull(scopeCreator);
  Preconditions.checkNotNull(topScope);

  Node externsAndJs = jsRoot.getParent();
  Preconditions.checkState(externsAndJs != null);
  Preconditions.checkState(
      externsRoot == null || externsAndJs.hasChild(externsRoot));

  if (externsRoot != null) {
    check(externsRoot, true);
  }
  check(jsRoot, false);
}
 
Example 15
Source File: jKali_003_t.java    From coming with MIT License 5 votes vote down vote up
/** Gets the r-value of a node returned by getBestLValue. */
static Node getRValueOfLValue(Node n) {
  Node parent = n.getParent();
  switch (parent.getType()) {
    case Token.ASSIGN:
      return n.getNext();
    case Token.VAR:
      return n.getFirstChild();
    case Token.FUNCTION:
      return parent;
  }
  return null;
}
 
Example 16
Source File: Cardumen_00152_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 17
Source File: jKali_003_t.java    From coming with MIT License 4 votes vote down vote up
/** Whether the node is a CATCH container BLOCK. */
static boolean isTryCatchNodeContainer(Node n) {
  Node parent = n.getParent();
  return parent.isTry()
      && parent.getFirstChild().getNext() == n;
}
 
Example 18
Source File: 1_FunctionInjector.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Determine which, if any, of the supported types the call site is.
 */
private CallSiteType classifyCallSite(Node callNode) {
  Node parent = callNode.getParent();
  Node grandParent = parent.getParent();

  // Verify the call site:
  if (NodeUtil.isExprCall(parent)) {
    // This is a simple call?  Example: "foo();".
    return CallSiteType.SIMPLE_CALL;
  } else if (NodeUtil.isExprAssign(grandParent)
      && !NodeUtil.isVarOrSimpleAssignLhs(callNode, parent)
      && parent.getFirstChild().isName()
      && !NodeUtil.isConstantName(parent.getFirstChild())) {
    // This is a simple assignment.  Example: "x = foo();"
    return CallSiteType.SIMPLE_ASSIGNMENT;
  } else if (parent.isName()
      && !NodeUtil.isConstantName(parent)
      && grandParent.isVar()
      && grandParent.hasOneChild()) {
    // This is a var declaration.  Example: "var x = foo();"
    // TODO(johnlenz): Should we be checking for constants on the
    // left-hand-side of the assignments and handling them as EXPRESSION?
    return CallSiteType.VAR_DECL_SIMPLE_ASSIGNMENT;
  } else {
    Node expressionRoot = ExpressionDecomposer.findExpressionRoot(callNode);
    if (expressionRoot != null) {
      ExpressionDecomposer decomposer = new ExpressionDecomposer(
          compiler, safeNameIdSupplier, knownConstants);
      DecompositionType type = decomposer.canExposeExpression(
          callNode);
      if (type == DecompositionType.MOVABLE) {
        return CallSiteType.EXPRESSION;
      } else if (type == DecompositionType.DECOMPOSABLE) {
        return CallSiteType.DECOMPOSABLE_EXPRESSION;
      } else {
        Preconditions.checkState(type == DecompositionType.UNDECOMPOSABLE);
      }
    }
  }

  return CallSiteType.UNSUPPORTED;
}
 
Example 19
Source File: PeepholeReplaceKnownMethods.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Try to fold .split() calls on strings
 */
private Node tryFoldStringSplit(Node n, Node stringNode, Node arg1) {
  if (late) {
    return n;
  }

  Preconditions.checkArgument(n.isCall());
  Preconditions.checkArgument(stringNode.isString());

  String separator = null;
  String stringValue = stringNode.getString();

  // Maximum number of possible splits
  int limit = stringValue.length() + 1;

  if (arg1 != null) {
    if (arg1.isString()) {
      separator = arg1.getString();
    } else if (!arg1.isNull()) {
      return n;
    }

    Node arg2 = arg1.getNext();
    if (arg2 != null) {
      if (arg2.isNumber()) {
        limit = Math.min((int) arg2.getDouble(), limit);
        if (limit < 0) {
          return n;
        }
      } else {
        return n;
      }
    }
  }

  // Split the string and convert the returned array into JS nodes
  String[] stringArray = jsSplit(stringValue, separator, limit);
  Node arrayOfStrings = IR.arraylit();
  for (int i = 0; i < stringArray.length; i++) {
    arrayOfStrings.addChildToBack(
        IR.string(stringArray[i]).srcref(stringNode));
  }

  Node parent = n.getParent();
  parent.replaceChild(n, arrayOfStrings);
  reportCodeChange();
  return arrayOfStrings;
}
 
Example 20
Source File: jKali_003_s.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());
  }
}