com.google.javascript.rhino.Node Java Examples

The following examples show how to use com.google.javascript.rhino.Node. 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_123_CodeGenerator_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @return Whether the Node is a DO or FUNCTION (with or without
 * labels).
 */
private boolean isOneExactlyFunctionOrDo(Node n) {
  if (n.isLabel()) {
    Node labeledStatement = n.getLastChild();
    if (!labeledStatement.isBlock()) {
      return isOneExactlyFunctionOrDo(labeledStatement);
    } else {
      // For labels with block children, we need to ensure that a
      // labeled FUNCTION or DO isn't generated when extraneous BLOCKs
      // are skipped.
      if (getNonEmptyChildCount(n, 2) == 1) {
        return isOneExactlyFunctionOrDo(getFirstNonEmptyChild(n));
      } else {
        // Either a empty statement or an block with more than one child,
        // way it isn't a FUNCTION or DO.
        return false;
      }
    }
  } else {
    return (n.isFunction() || n.isDo());
  }
}
 
Example #2
Source File: Cardumen_00249_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Remove all references to a parameter, otherwise simplify the known
 * references.
 * @return Whether all the references were removed.
 */
private boolean canRemoveArgFromCallSites(Node function, int argIndex) {
  Definition definition = getFunctionDefinition(function);

  // Check all the call sites.
  for (UseSite site : defFinder.getUseSites(definition)) {
    if (isModifiableCallSite(site)) {
      Node arg = getArgumentForCallOrNewOrDotCall(site, argIndex);
      // TODO(johnlenz): try to remove parameters with side-effects by
      // decomposing the call expression.
      if (arg != null && NodeUtil.mayHaveSideEffects(arg, compiler)) {
        return false;
      }
    } else {
      return false;
    }
  }

  return true;
}
 
Example #3
Source File: jMutRepair_003_t.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: RescopeGlobalSymbols.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void process(Node externs, Node root) {
  // Make the name of the globalSymbolNamespace an extern.
  if (addExtern) {
    addExternForGlobalSymbolNamespace();
  }
  // Rewrite all references to global symbols to properties of a
  // single symbol by:
  // (If necessary the 3 traversals could be combined. They are left
  // separate for readability reasons.)
  // 1. turning global named function statements into var assignments.
  NodeTraversal.traverse(compiler, root,
      new RewriteGlobalFunctionStatementsToVarAssignmentsCallback());
  // 2. rewriting all references to be property accesses of the single symbol.
  NodeTraversal.traverse(compiler, root, new RewriteScopeCallback());
  // 3. removing the var from every statement in global scope.
  NodeTraversal.traverse(compiler, root, new RemoveGlobalVarCallback());

  // Extra pass which makes all extern global symbols reference window
  // explicitly.
  NodeTraversal.traverse(compiler, root,
      new MakeExternsReferenceWindowExplicitly());
}
 
Example #5
Source File: Closure_124_ExploitAssigns_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Try to collapse the given assign into subsequent expressions.
 */
private void collapseAssign(Node assign, Node expr,
    Node exprParent) {
  Node leftValue = assign.getFirstChild();
  Node rightValue = leftValue.getNext();
  if (isCollapsibleValue(leftValue, true) &&
      collapseAssignEqualTo(expr, exprParent, leftValue)) {
    reportCodeChange();
  } else if (isCollapsibleValue(rightValue, false) &&
      collapseAssignEqualTo(expr, exprParent, rightValue)) {
    reportCodeChange();
  } else if (rightValue.isAssign()) {
    // Recursively deal with nested assigns.
    collapseAssign(rightValue, expr, exprParent);
  }
}
 
Example #6
Source File: 1_ClosureCodingConvention.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
private static String extractClassNameIfGoog(Node node, Node parent,
      String functionName){
    String className = null;
    if (NodeUtil.isExprCall(parent)) {
      Node callee = node.getFirstChild();
      if (callee != null && callee.getType() == Token.GETPROP) {
        String qualifiedName = callee.getQualifiedName();
        if (functionName.equals(qualifiedName)) {
          Node target = callee.getNext();
// start of generated patch
if(target!=null&&target.getType()==Token.STRING){
className=target.getString();
}
// end of generated patch
/* start of original code
          if (target != null) {
            className = target.getString();
          }
 end of original code*/
        }
      }
    }
    return className;
  }
 
Example #7
Source File: PeepholeSubstituteAlternateSyntax.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private boolean statementMustExitParent(Node n) {
  switch (n.getType()) {
    case Token.THROW:
    case Token.RETURN:
      return true;
    case Token.BLOCK:
      if (n.hasChildren()) {
        Node child = n.getLastChild();
        return statementMustExitParent(child);
      }
      return false;
    // TODO(johnlenz): handle TRY/FINALLY
    case Token.FUNCTION:
    default:
      return false;
  }
}
 
Example #8
Source File: Closure_57_ClosureCodingConvention_t.java    From coming with MIT License 6 votes vote down vote up
private static String extractClassNameIfGoog(Node node, Node parent,
    String functionName){
  String className = null;
  if (NodeUtil.isExprCall(parent)) {
    Node callee = node.getFirstChild();
    if (callee != null && callee.getType() == Token.GETPROP) {
      String qualifiedName = callee.getQualifiedName();
      if (functionName.equals(qualifiedName)) {
        Node target = callee.getNext();
        if (target != null && target.getType() == Token.STRING) {
          className = target.getString();
        }
      }
    }
  }
  return className;
}
 
Example #9
Source File: Closure_18_Compiler_t.java    From coming with MIT License 6 votes vote down vote up
/** Load a library as a resource */
@VisibleForTesting
Node loadLibraryCode(String resourceName) {
  String originalCode;
  try {
    originalCode = CharStreams.toString(new InputStreamReader(
        Compiler.class.getResourceAsStream(
            String.format("js/%s.js", resourceName)),
        Charsets.UTF_8));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  return Normalize.parseAndNormalizeSyntheticCode(
      this, originalCode,
      String.format("jscomp_%s_", resourceName));
}
 
Example #10
Source File: jMutRepair_003_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * @return The number of times the the predicate is true for the node
 * or any of its children.
 */
static int getCount(
    Node n, Predicate<Node> pred, Predicate<Node> traverseChildrenPred) {
  int total = 0;

  if (pred.apply(n)) {
    total++;
  }

  if (traverseChildrenPred.apply(n)) {
    for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
      total += getCount(c, pred, traverseChildrenPred);
    }
  }

  return total;
}
 
Example #11
Source File: Closure_106_GlobalNamespace_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Tries to get the doc info for a given declaration ref.
 */
private static JSDocInfo getDocInfoForDeclaration(Ref ref) {
  if (ref.node != null) {
    Node refParent = ref.node.getParent();
    switch (refParent.getType()) {
      case Token.FUNCTION:
      case Token.ASSIGN:
        return refParent.getJSDocInfo();
      case Token.VAR:
        return ref.node == refParent.getFirstChild() ?
            refParent.getJSDocInfo() : ref.node.getJSDocInfo();
    }
  }

  return null;
}
 
Example #12
Source File: ParserTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Verify that the given code has the given parse errors.
 * @return If in IDE mode, returns a partial tree.
 */
private Node parseError(String string, String... errors) {
  TestErrorReporter testErrorReporter = new TestErrorReporter(errors, null);
  Node script = null;
  try {
    StaticSourceFile file = new SimpleSourceFile("input", false);
    script = ParserRunner.parse(
        file, string, ParserRunner.createConfig(isIdeMode, mode, false),
        testErrorReporter, Logger.getAnonymousLogger()).ast;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  // verifying that all warnings were seen
  assertTrue(testErrorReporter.hasEncounteredAllErrors());
  assertTrue(testErrorReporter.hasEncounteredAllWarnings());

  return script;
}
 
Example #13
Source File: Nopol2017_0025_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * ResultType := <empty> | ':' void | ':' TypeExpression
 */
private Node parseResultType(JsDocToken token) {
  skipEOLs();
  if (!match(JsDocToken.COLON)) {
    return newNode(Token.EMPTY);
  }

  token = next();
  skipEOLs();
  if (match(JsDocToken.STRING) && "void".equals(stream.getString())) {
    next();
    return newNode(Token.VOID);
  } else {
    return parseTypeExpression(next());
  }
}
 
Example #14
Source File: Closure_23_PeepholeFoldConstants_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * @param value The value to compare to "undefined"
 * @param op The boolean op to compare with
 * @return Whether the boolean op is true or false
 */
private boolean compareToUndefined(Node value, int op) {
  Preconditions.checkState(NodeUtil.isLiteralValue(value, true));
  boolean valueUndefined = NodeUtil.isUndefined(value);
  boolean valueNull = (Token.NULL == value.getType());
  boolean equivalent = valueUndefined || valueNull;
  switch (op) {
    case Token.EQ:
      // undefined is only equal to null or an undefined value
      return equivalent;
    case Token.NE:
      return !equivalent;
    case Token.SHEQ:
      return valueUndefined;
    case Token.SHNE:
      return !valueUndefined;
    case Token.LT:
    case Token.GT:
    case Token.LE:
    case Token.GE:
      return false;
    default:
      throw new IllegalStateException("unexpected.");
  }
}
 
Example #15
Source File: Closure_93_ProcessClosurePrimitives_s.java    From coming with MIT License 5 votes vote down vote up
ProvidedName(String namespace, Node node, JSModule module,
    boolean explicit) {
  Preconditions.checkArgument(
      node == null /* The base case */ ||
      NodeUtil.isExpressionNode(node));
  this.namespace = namespace;
  this.firstNode = node;
  this.firstModule = module;

  addProvide(node, module, explicit);
}
 
Example #16
Source File: Closure_81_IRFactory_s.java    From coming with MIT License 5 votes vote down vote up
@Override
Node processSwitchStatement(SwitchStatement statementNode) {
  Node node = newNode(Token.SWITCH,
      transform(statementNode.getExpression()));
  for (AstNode child : statementNode.getCases()) {
    node.addChildToBack(transform(child));
  }
  return node;
}
 
Example #17
Source File: Closure_18_Compiler_t.java    From coming with MIT License 5 votes vote down vote up
/** Control Flow Analysis. */
ControlFlowGraph<Node> computeCFG() {
  logger.fine("Computing Control Flow Graph");
  Tracer tracer = newTracer("computeCFG");
  ControlFlowAnalysis cfa = new ControlFlowAnalysis(this, true, false);
  process(cfa);
  stopTracer(tracer, "computeCFG");
  return cfa.getCfg();
}
 
Example #18
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Expressions such as [foo() + 'a' + 'b'] generate parse trees
 * where no node has two const children ((foo() + 'a') + 'b'), so
 * tryFoldAdd() won't fold it -- tryFoldLeftChildAdd() will (for Strings).
 * Specifically it folds Add exprssions where:
 *  - The left child is also and add expression
 *  - The right child is a constant value
 *  - The left child's right child is a STRING constant.
 *
 * WARNING: If javascript ever adds operator overloading, this will
 * probably stop being correct.
 */
void tryFoldLeftChildAdd(NodeTraversal t, Node n, Node left, Node right,
                         Node parent) {

  if (NodeUtil.isLiteralValue(right) &&
      left.getType() == Token.ADD &&
      left.getChildCount() == 2) {

    Node ll = left.getFirstChild();
    Node lr = ll.getNext();

    // Left's right child MUST be a string. We would not want to fold
    // foo() + 2 + 'a' because we don't know what foo() will return, and
    // therefore we don't know if left is a string concat, or a numeric add.
    if (lr.getType() != Token.STRING)
      return;

    String leftString = NodeUtil.getStringValue(lr);
    String rightString = NodeUtil.getStringValue(right);
    if (leftString != null && rightString != null) {
      left.removeChild(ll);
      String result = leftString + rightString;
      n.replaceChild(left, ll);
      n.replaceChild(right, Node.newString(result));
      t.getCompiler().reportCodeChange();
    }
  }
}
 
Example #19
Source File: Closure_21_CheckSideEffects_t.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 #20
Source File: Closure_84_IRFactory_t.java    From coming with MIT License 5 votes vote down vote up
@Override
Node processContinueStatement(ContinueStatement statementNode) {
  Node node = newNode(Token.CONTINUE);
  if (statementNode.getLabel() != null) {
    Node labelName = transform(statementNode.getLabel());
    // Change the NAME to LABEL_NAME
    labelName.setType(Token.LABEL_NAME);
    node.addChildToBack(labelName);
  }
  return node;
}
 
Example #21
Source File: Closure_114_NameAnalyzer_s.java    From coming with MIT License 5 votes vote down vote up
private void recordAssignment(NodeTraversal t, Node n, Node recordNode) {
  Node nameNode = n.getFirstChild();
  Node parent = n.getParent();
  NameInformation ns = createNameInformation(t, nameNode);
  if (ns != null) {
    if (parent.isFor() && !NodeUtil.isForIn(parent)) {
      // Patch for assignments that appear in the init,
      // condition or iteration part of a FOR loop.  Without
      // this change, all 3 of those parts try to claim the for
      // loop as their dependency scope.  The last assignment in
      // those three fields wins, which can result in incorrect
      // reference edges between referenced and assigned variables.
      //
      // TODO(user) revisit the dependency scope calculation
      // logic.
      if (parent.getFirstChild().getNext() != n) {
        recordDepScope(recordNode, ns);
      } else {
        recordDepScope(nameNode, ns);
      }
    } else {
      // The rhs of the assignment is the caller, so it's used by the
      // context. Don't associate it w/ the lhs.
      // FYI: this fixes only the specific case where the assignment is the
      // caller expression, but it could be nested deeper in the caller and
      // we would still get a bug.
      // See testAssignWithCall2 for an example of this.
      recordDepScope(recordNode, ns);
    }
  }
}
 
Example #22
Source File: Closure_42_IRFactory_s.java    From coming with MIT License 5 votes vote down vote up
@Override
Node processConditionalExpression(ConditionalExpression exprNode) {
  return newNode(
      Token.HOOK,
      transform(exprNode.getTestExpression()),
      transform(exprNode.getTrueExpression()),
      transform(exprNode.getFalseExpression()));
}
 
Example #23
Source File: Nopol2017_0025_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * ParamTypeExpressionAnnotation :=
 *     '{' OptionalParameterType '}' |
 *     '{' TopLevelTypeExpression '}' |
 *     '{' '...' TopLevelTypeExpression '}'
 *
 * OptionalParameterType :=
 *     TopLevelTypeExpression '='
 */
private Node parseParamTypeExpressionAnnotation(JsDocToken token) {
  Preconditions.checkArgument(token == JsDocToken.LC);

  skipEOLs();

  boolean restArg = false;
  token = next();
  if (token == JsDocToken.ELLIPSIS) {
    token = next();
    if (token == JsDocToken.RC) {
      // EMPTY represents the UNKNOWN type in the Type AST.
      return wrapNode(Token.ELLIPSIS, IR.empty());
    }
    restArg = true;
  }

  Node typeNode = parseTopLevelTypeExpression(token);
  if (typeNode != null) {
    skipEOLs();
    if (restArg) {
      typeNode = wrapNode(Token.ELLIPSIS, typeNode);
    } else if (match(JsDocToken.EQUALS)) {
      next();
      skipEOLs();
      typeNode = wrapNode(Token.EQUALS, typeNode);
    }

    if (!match(JsDocToken.RC)) {
      reportTypeSyntaxWarning("msg.jsdoc.missing.rc");
    } else {
      next();
    }
  }

  return typeNode;
}
 
Example #24
Source File: Cardumen_00200_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * A pre-order traversal, calling Visitor.visit for each child matching
 * the predicate.
 */
static void visitPreOrder(Node node,
                   Visitor visitor,
                   Predicate<Node> traverseChildrenPred) {
  visitor.visit(node);

  if (traverseChildrenPred.apply(node)) {
    for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
      visitPreOrder(c, visitor, traverseChildrenPred);
    }
  }
}
 
Example #25
Source File: 1_ControlFlowAnalysis.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the next sibling (including itself) of one of the given types.
 */
private static Node getNextSiblingOfType(Node first, int ... types) {
  for (Node c = first; c != null; c = c.getNext()) {
    for (int type : types) {
      if (c.getType() == type) {
        return c;
      }
    }
  }
  return null;
}
 
Example #26
Source File: Closure_31_Compiler_t.java    From coming with MIT License 5 votes vote down vote up
@Override
void updateGlobalVarReferences(Map<Var, ReferenceCollection> refMapPatch,
    Node collectionRoot) {
  Preconditions.checkState(collectionRoot.isScript()
      || collectionRoot.isBlock());
  if (globalRefMap == null) {
    globalRefMap = new GlobalVarReferenceMap(getInputsInOrder(),
        getExternsInOrder());
  }
  globalRefMap.updateGlobalVarReferences(refMapPatch, collectionRoot);
}
 
Example #27
Source File: Closure_54_TypedScopeCreator_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Visit a node in a local scope, and add any local variables or catch
 * parameters into the local symbol table.
 *
 * @param t The node traversal.
 * @param n The node being visited.
 * @param parent The parent of n
 */
@Override public void visit(NodeTraversal t, Node n, Node parent) {
  if (n == scope.getRootNode()) return;

  if (n.getType() == Token.LP && parent == scope.getRootNode()) {
    handleFunctionInputs(parent);
    return;
  }

  super.visit(t, n, parent);
}
 
Example #28
Source File: LineNumberCheck.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.isScript()) {
    requiresLineNumbers = false;
  } else if (requiresLineNumbers) {
    if (n.getLineno() == -1) {
      // The tree version of the node is really the best diagnostic
      // info we have to offer here.
      compiler.report(
          t.makeError(n, MISSING_LINE_INFO,
              n.toStringTree()));
    }
  }
}
 
Example #29
Source File: jMutRepair_003_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param knownConstants A set of names known to be constant value at
 * node 'n' (such as locals that are last written before n can execute).
 * @return Whether the tree can be affected by side-effects or
 * has side-effects.
 */
static boolean canBeSideEffected(Node n, Set<String> knownConstants) {
  switch (n.getType()) {
    case Token.CALL:
    case Token.NEW:
      // Function calls or constructor can reference changed values.
      // TODO(johnlenz): Add some mechanism for determining that functions
      // are unaffected by side effects.
      return true;
    case Token.NAME:
      // Non-constant names values may have been changed.
      return !isConstantName(n)
          && !knownConstants.contains(n.getString());

    // Properties on constant NAMEs can still be side-effected.
    case Token.GETPROP:
    case Token.GETELEM:
      return true;

    case Token.FUNCTION:
      // Function expression are not changed by side-effects,
      // and function declarations are not part of expressions.
      Preconditions.checkState(isFunctionExpression(n));
      return false;
  }

  for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
    if (canBeSideEffected(c, knownConstants)) {
      return true;
    }
  }

  return false;
}
 
Example #30
Source File: Cardumen_00203_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * For each unused function parameter, determine if it can be removed
 * from all the call sites, if so, remove it from the function signature
 * and the call sites otherwise replace the unused value where possible
 * with a constant (0).
 *
 * @param scope The function scope
 * @param function The function
 * @param param The current parameter node in the parameter list.
 * @param paramIndex The index of the current parameter
 * @param canChangeSignature Whether function signature can be change.
 * @return Whether there is a following function parameter.
 */
private boolean markUnreferencedFunctionArgs(
    Scope scope, Node function, Set<Var> referenced,
    Node param, int paramIndex,
    boolean canChangeSignature) {
  if (param != null) {
    // Take care of the following siblings first.
    boolean hasFollowing = markUnreferencedFunctionArgs(
        scope, function, referenced, param.getNext(), paramIndex+1,
        canChangeSignature);

    Var var = scope.getVar(param.getString());
    if (!referenced.contains(var)) {
      Preconditions.checkNotNull(var);

      // Remove call parameter if we can generally change the signature
      // or if it is the last parameter in the parameter list.
      boolean modifyAllCallSites = canChangeSignature || !hasFollowing;
      if (modifyAllCallSites) {
        modifyAllCallSites = canRemoveArgFromCallSites(
            function, paramIndex);
      }

      tryRemoveArgFromCallSites(function, paramIndex, modifyAllCallSites);

      // Remove an unused function parameter if all the call sites can
      // be modified to remove it, or if it is the last parameter.
      if (modifyAllCallSites || !hasFollowing) {
        toRemove.add(param);
        return hasFollowing;
      }
    }
    return true;
  } else {
    // Anything past the last formal parameter can be removed from the call
    // sites.
    tryRemoveAllFollowingArgs(function, paramIndex-1);
    return false;
  }
}