com.google.javascript.rhino.IR Java Examples

The following examples show how to use com.google.javascript.rhino.IR. 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: jMutRepair_003_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @return An appropriate AST node for the double value.
 */
static Node numberNode(double value, Node srcref) {
  Node result;
  if (Double.isNaN(value)) {
    result = IR.name("NaN");
  } else if (value == Double.POSITIVE_INFINITY) {
    result = IR.name("Infinity");
  } else if (value == Double.NEGATIVE_INFINITY) {
    result = IR.neg(IR.name("Infinity"));
  } else {
    result = IR.number(value);
  }
  if (srcref != null) {
    result.srcrefTree(srcref);
  }
  return result;
}
 
Example #2
Source File: Cardumen_0014_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given a node tree, finds all the VAR declarations in that tree that are
 * not in an inner scope. Then adds a new VAR node at the top of the current
 * scope that redeclares them, if necessary.
 */
static void redeclareVarsInsideBranch(Node branch) {
  Collection<Node> vars = getVarsDeclaredInBranch(branch);
  if (vars.isEmpty()) {
    return;
  }

  Node parent = getAddingRoot(branch);
  for (Node nameNode : vars) {
    Node var = IR.var(
        IR.name(nameNode.getString())
            .srcref(nameNode))
        .srcref(nameNode);
    copyNameAnnotations(nameNode, var.getFirstChild());
    parent.addChildToFront(var);
  }
}
 
Example #3
Source File: Cardumen_00151_s.java    From coming with MIT License 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 #4
Source File: Closure_23_PeepholeFoldConstants_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Try to fold an ADD node with constant operands
 */
private Node tryFoldAddConstantString(Node n, Node left, Node right) {
  if (left.isString() ||
      right.isString()) {
    // Add strings.
    String leftString = NodeUtil.getStringValue(left);
    String rightString = NodeUtil.getStringValue(right);
    if (leftString != null && rightString != null) {
      Node newStringNode = IR.string(leftString + rightString);
      n.getParent().replaceChild(n, newStringNode);
      reportCodeChange();
      return newStringNode;
    }
  }



  return n;
}
 
Example #5
Source File: Closure_129_PrepareAst_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Add blocks to IF, WHILE, DO, etc.
 */
private void normalizeBlocks(Node n) {
  if (NodeUtil.isControlStructure(n)
      && !n.isLabel()
      && !n.isSwitch()) {
    for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
      if (NodeUtil.isControlStructureCodeBlock(n,c) &&
          !c.isBlock()) {
        Node newBlock = IR.block().srcref(n);
        n.replaceChild(c, newBlock);
        if (!c.isEmpty()) {
          newBlock.addChildrenToFront(c);
        } else {
          newBlock.setWasEmptyNode(true);
        }
        c = newBlock;
        reportChange();
      }
    }
  }
}
 
Example #6
Source File: Cardumen_0087_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example #7
Source File: Closure_32_JsDocInfoParser_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * TypeExpressionList := TopLevelTypeExpression
 *     | TopLevelTypeExpression ',' TypeExpressionList
 */
private Node parseTypeExpressionList(JsDocToken token) {
  Node typeExpr = parseTopLevelTypeExpression(token);
  if (typeExpr == null) {
    return null;
  }
  Node typeList = IR.block();
  typeList.addChildToBack(typeExpr);
  while (match(JsDocToken.COMMA)) {
    next();
    skipEOLs();
    typeExpr = parseTopLevelTypeExpression(next());
    if (typeExpr == null) {
      return null;
    }
    typeList.addChildToBack(typeExpr);
  }
  return typeList;
}
 
Example #8
Source File: Closure_20_PeepholeSubstituteAlternateSyntax_s.java    From coming with MIT License 6 votes vote down vote up
private Node tryFoldSimpleFunctionCall(Node n) {
  Preconditions.checkState(n.isCall());
  Node callTarget = n.getFirstChild();
  if (callTarget != null && callTarget.isName() &&
        callTarget.getString().equals("String")) {
    // Fold String(a) to '' + (a) on immutable literals,
    // which allows further optimizations
    //
    // We can't do this in the general case, because String(a) has
    // slightly different semantics than '' + (a). See
    // http://code.google.com/p/closure-compiler/issues/detail?id=759
    Node value = callTarget.getNext();
    if (value != null) {
      Node addition = IR.add(
          IR.string("").srcref(callTarget),
          value.detachFromParent());
      n.getParent().replaceChild(n, addition);
      reportCodeChange();
      return addition;
    }
  }
  return n;
}
 
Example #9
Source File: NodeUtil.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example #10
Source File: Cardumen_00200_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given a node tree, finds all the VAR declarations in that tree that are
 * not in an inner scope. Then adds a new VAR node at the top of the current
 * scope that redeclares them, if necessary.
 */
static void redeclareVarsInsideBranch(Node branch) {
  Collection<Node> vars = getVarsDeclaredInBranch(branch);
  if (vars.isEmpty()) {
    return;
  }

  Node parent = getAddingRoot(branch);
  for (Node nameNode : vars) {
    Node var = IR.var(
        IR.name(nameNode.getString())
            .srcref(nameNode))
        .srcref(nameNode);
    copyNameAnnotations(nameNode, var.getFirstChild());
    parent.addChildToFront(var);
  }
}
 
Example #11
Source File: Nopol2017_0010_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a dotted namespace assignment expression
 * (e.g. <code>foo.bar = {};</code>).
 */
private Node makeAssignmentExprNode() {
  Node decl = IR.exprResult(
      IR.assign(
          NodeUtil.newQualifiedNameNode(
              compiler.getCodingConvention(), namespace,
              firstNode /* real source info will be filled in below */,
              namespace),
          createNamespaceLiteral()));
  decl.putBooleanProp(Node.IS_NAMESPACE, true);
  if (candidateDefinition == null) {
    decl.getFirstChild().setJSDocInfo(createConstantJsDoc());
  }
  Preconditions.checkState(isNamespacePlaceholder(decl));
  setSourceInfo(decl);
  return decl;
}
 
Example #12
Source File: Cardumen_0017_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * TypeExpressionList := TopLevelTypeExpression
 *     | TopLevelTypeExpression ',' TypeExpressionList
 */
private Node parseTypeExpressionList(JsDocToken token) {
  Node typeExpr = parseTopLevelTypeExpression(token);
  if (typeExpr == null) {
    return null;
  }
  Node typeList = IR.block();
  typeList.addChildToBack(typeExpr);
  while (match(JsDocToken.COMMA)) {
    next();
    skipEOLs();
    typeExpr = parseTopLevelTypeExpression(next());
    if (typeExpr == null) {
      return null;
    }
    typeList.addChildToBack(typeExpr);
  }
  return typeList;
}
 
Example #13
Source File: Cardumen_0014_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Creates a node representing a qualified name.
 *
 * @param name A qualified name (e.g. "foo" or "foo.bar.baz")
 * @return A NAME or GETPROP node
 */
public static Node newQualifiedNameNode(
    CodingConvention convention, String name) {
  int endPos = name.indexOf('.');
  if (endPos == -1) {
    return newName(convention, name);
  }
  Node node = newName(convention, name.substring(0, endPos));
  int startPos;
  do {
    startPos = endPos + 1;
    endPos = name.indexOf('.', startPos);
    String part = (endPos == -1
                   ? name.substring(startPos)
                   : name.substring(startPos, endPos));
    Node propNode = IR.string(part);
    if (convention.isConstantKey(part)) {
      propNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
    node = IR.getprop(node, propNode);
  } while (endPos != -1);

  return node;
}
 
Example #14
Source File: Closure_133_JsDocInfoParser_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * TypeExpressionList := TopLevelTypeExpression
 *     | TopLevelTypeExpression ',' TypeExpressionList
 */
private Node parseTypeExpressionList(JsDocToken token) {
  Node typeExpr = parseTopLevelTypeExpression(token);
  if (typeExpr == null) {
    return null;
  }
  Node typeList = IR.block();
  typeList.addChildToBack(typeExpr);
  while (match(JsDocToken.COMMA)) {
    next();
    skipEOLs();
    typeExpr = parseTopLevelTypeExpression(next());
    if (typeExpr == null) {
      return null;
    }
    typeList.addChildToBack(typeExpr);
  }
  return typeList;
}
 
Example #15
Source File: Cardumen_0087_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given a node tree, finds all the VAR declarations in that tree that are
 * not in an inner scope. Then adds a new VAR node at the top of the current
 * scope that redeclares them, if necessary.
 */
static void redeclareVarsInsideBranch(Node branch) {
  Collection<Node> vars = getVarsDeclaredInBranch(branch);
  if (vars.isEmpty()) {
    return;
  }

  Node parent = getAddingRoot(branch);
  for (Node nameNode : vars) {
    Node var = IR.var(
        IR.name(nameNode.getString())
            .srcref(nameNode))
        .srcref(nameNode);
    copyNameAnnotations(nameNode, var.getFirstChild());
    parent.addChildToFront(var);
  }
}
 
Example #16
Source File: jKali_003_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @return An appropriate AST node for the double value.
 */
static Node numberNode(double value, Node srcref) {
  Node result;
  if (Double.isNaN(value)) {
    result = IR.name("NaN");
  } else if (value == Double.POSITIVE_INFINITY) {
    result = IR.name("Infinity");
  } else if (value == Double.NEGATIVE_INFINITY) {
    result = IR.neg(IR.name("Infinity"));
  } else {
    result = IR.number(value);
  }
  if (srcref != null) {
    result.srcrefTree(srcref);
  }
  return result;
}
 
Example #17
Source File: JGenProg2017_00108_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Protect side-effect free nodes by making them parameters
 * to a extern function call.  This call will be removed
 * after all the optimizations passes have run.
 */
private void protectSideEffects() {
  if (!problemNodes.isEmpty()) {
    addExtern();
    for (Node n : problemNodes) {
      Node name = IR.name(PROTECTOR_FN).srcref(n);
      name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
      Node replacement = IR.call(name).srcref(n);
      replacement.putBooleanProp(Node.FREE_CALL, true);
      n.getParent().replaceChild(n, replacement);
      replacement.addChildToBack(n);
    }
    compiler.reportCodeChange();
  }
}
 
Example #18
Source File: Cardumen_0021_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace the current assign with its right hand side.
 */
void remove() {
  Node parent = assignNode.getParent();
  if (mayHaveSecondarySideEffects) {
    Node replacement = assignNode.getLastChild().detachFromParent();

    // Aggregate any expressions in GETELEMs.
    for (Node current = assignNode.getFirstChild();
         !current.isName();
         current = current.getFirstChild()) {
      if (current.isGetElem()) {
        replacement = IR.comma(
            current.getLastChild().detachFromParent(), replacement);
        replacement.copyInformationFrom(current);
      }
    }

    parent.replaceChild(assignNode, replacement);
  } else {
    Node gramps = parent.getParent();
    if (parent.isExprResult()) {
      gramps.removeChild(parent);
    } else {
      parent.replaceChild(assignNode,
          assignNode.getLastChild().detachFromParent());
    }
  }
}
 
Example #19
Source File: Nopol2017_0010_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * There are some special cases where clients of the compiler
 * do not run TypedScopeCreator after running this pass.
 * So always give the namespace literal a type.
 */
private Node createNamespaceLiteral() {
  Node objlit = IR.objectlit();
  objlit.setJSType(
      compiler.getTypeRegistry().createAnonymousObjectType(null));
  return objlit;
}
 
Example #20
Source File: jKali_006_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Protect side-effect free nodes by making them parameters
 * to a extern function call.  This call will be removed
 * after all the optimizations passes have run.
 */
private void protectSideEffects() {
  if (!problemNodes.isEmpty()) {
    addExtern();
    for (Node n : problemNodes) {
      Node name = IR.name(PROTECTOR_FN).srcref(n);
      name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
      Node replacement = IR.call(name).srcref(n);
      replacement.putBooleanProp(Node.FREE_CALL, true);
      n.getParent().replaceChild(n, replacement);
      replacement.addChildToBack(n);
    }
    compiler.reportCodeChange();
  }
}
 
Example #21
Source File: AstParallelizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static AstParallelizer createNewFileLevelAstParallelizer(Node root) {

    // Split at every node that has a file name prop.
    Predicate<Node> shouldSplit = new Predicate<Node>() {
      @Override
      public boolean apply(Node input) {
        return input.getSourceFileName() != null;
      }
    };

    // Use a string as place holder.
    Supplier<Node> placeHolders = new Supplier<Node>() {
      @Override
      public Node get() {
        return NodeUtil.newExpr(IR.string(TEMP_NAME));
      }
    };

    // Only traverse blocks.
    Predicate<Node> shouldTraverse = new Predicate<Node>() {
      @Override
      public boolean apply(Node n) {
        return n.isBlock();
      }
    };
    return new AstParallelizer(
        shouldSplit, shouldTraverse, placeHolders, root, false);
  }
 
Example #22
Source File: ProcessTweaks.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes all CALL nodes in the given TweakInfos, replacing calls to getter
 * functions with the tweak's default value.
 */
private boolean stripAllCalls(Map<String, TweakInfo> tweakInfos) {
  for (TweakInfo tweakInfo : tweakInfos.values()) {
    boolean isRegistered = tweakInfo.isRegistered();
    for (TweakFunctionCall functionCall : tweakInfo.functionCalls) {
      Node callNode = functionCall.callNode;
      Node parent = callNode.getParent();
      if (functionCall.tweakFunc.isGetterFunction()) {
        Node newValue;
        if (isRegistered) {
          newValue = tweakInfo.getDefaultValueNode().cloneNode();
        } else {
          // When we find a getter of an unregistered tweak, there has
          // already been a warning about it, so now just use a default
          // value when stripping.
          TweakFunction registerFunction =
              functionCall.tweakFunc.registerFunction;
          newValue = registerFunction.createDefaultValueNode();
        }
        parent.replaceChild(callNode, newValue);
      } else {
        Node voidZeroNode = IR.voidNode(IR.number(0).srcref(callNode))
            .srcref(callNode);
        parent.replaceChild(callNode, voidZeroNode);
      }
    }
  }
  return !tweakInfos.isEmpty();
}
 
Example #23
Source File: Cardumen_0017_t.java    From coming with MIT License 5 votes vote down vote up
private Node createTemplateNode() {
  // The Node type choice is arbitrary.
  Node templateNode = IR.script();
  templateNode.setStaticSourceFile(
    this.associatedNode != null ?
    this.associatedNode.getStaticSourceFile() :
    null);
  return templateNode;
}
 
Example #24
Source File: jKali_003_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a VAR node containing the given name and initial value expression.
 */
static Node newVarNode(String name, Node value) {
  Node nodeName = IR.name(name);
  if (value != null) {
    Preconditions.checkState(value.getNext() == null);
    nodeName.addChildToBack(value);
    nodeName.srcref(value);
  }
  Node var = IR.var(nodeName).srcref(nodeName);

  return var;
}
 
Example #25
Source File: Cardumen_0087_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * A new CALL node with the "FREE_CALL" set based on call target.
 */
static Node newCallNode(Node callTarget, Node... parameters) {
  boolean isFreeCall = !isGet(callTarget);
  Node call = IR.call(callTarget);
  call.putBooleanProp(Node.FREE_CALL, isFreeCall);
  for (Node parameter : parameters) {
    call.addChildToBack(parameter);
  }
  return call;
}
 
Example #26
Source File: Cardumen_0014_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Add a finally block if one does not exist.
 */
static void maybeAddFinally(Node tryNode) {
  Preconditions.checkState(tryNode.isTry());
  if (!NodeUtil.hasFinally(tryNode)) {
    tryNode.addChildrenToBack(IR.block().srcref(tryNode));
  }
}
 
Example #27
Source File: Cardumen_0093_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Replace the current assign with its right hand side.
 */
void remove() {
  Node parent = assignNode.getParent();
  if (mayHaveSecondarySideEffects) {
    Node replacement = assignNode.getLastChild().detachFromParent();

    // Aggregate any expressions in GETELEMs.
    for (Node current = assignNode.getFirstChild();
         !current.isName();
         current = current.getFirstChild()) {
      if (current.isGetElem()) {
        replacement = IR.comma(
            current.getLastChild().detachFromParent(), replacement);
        replacement.copyInformationFrom(current);
      }
    }

    parent.replaceChild(assignNode, replacement);
  } else {
    Node gramps = parent.getParent();
    if (parent.isExprResult()) {
      gramps.removeChild(parent);
    } else {
      parent.replaceChild(assignNode,
          assignNode.getLastChild().detachFromParent());
    }
  }
}
 
Example #28
Source File: Cardumen_0017_s.java    From coming with MIT License 5 votes vote down vote up
private Node createTemplateNode() {
  // The Node type choice is arbitrary.
  Node templateNode = IR.script();
  templateNode.setStaticSourceFile(
    this.associatedNode != null ?
    this.associatedNode.getStaticSourceFile() :
    null);
  return templateNode;
}
 
Example #29
Source File: jKali_0043_t.java    From coming with MIT License 5 votes vote down vote up
private void addExtern() {
  Node name = IR.name(PROTECTOR_FN);
  name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
  Node var = IR.var(name);
  // Add "@noalias" so we can strip the method when AliasExternals is enabled.
  JSDocInfoBuilder builder = new JSDocInfoBuilder(false);
  builder.recordNoAlias();
  var.setJSDocInfo(builder.build(var));
  CompilerInput input = compiler.getSynthesizedExternsInput();
  input.getAstRoot(compiler).addChildrenToBack(var);
  compiler.reportCodeChange();
}
 
Example #30
Source File: Cardumen_00200_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Create a VAR node containing the given name and initial value expression.
 */
static Node newVarNode(String name, Node value) {
  Node nodeName = IR.name(name);
  if (value != null) {
    Preconditions.checkState(value.getNext() == null);
    nodeName.addChildToBack(value);
    nodeName.srcref(value);
  }
  Node var = IR.var(nodeName).srcref(nodeName);

  return var;
}