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

The following examples show how to use com.google.javascript.rhino.Node#isScript() . 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: NodeModulePass.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
  if (n.isScript()) {
    checkState(currentModule == null);

    String sourceName = n.getSourceFileName();
    Path path = inputFs.getPath(n.getSourceFileName());
    if (!nodeLibrary.isModulePath(sourceName) && !modulePaths.contains(path)) {
      return false;
    }

    if (nodeLibrary.isModulePath(sourceName)) {
      currentModule = nodeLibrary.getIdFromPath(sourceName);
    } else {
      Module module = globalSymbolTable.getModule(path);
      checkNotNull(module, "module not found: %s", path);
      if (module.isEs6()) {
        return false;
      }
      currentModule = module.getId().getOriginalName();
    }

    traverse(t.getCompiler(), n, new SplitRequireDeclarations());
  }
  return true;
}
 
Example 2
Source File: GlobalVarReferenceMap.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Updates the internal reference map based on the provided parameters. If
 * {@code scriptRoot} is not SCRIPT, it basically replaces the internal map
 * with the new one, otherwise it replaces all the information associated to
 * the given script.
 *
 * @param refMapPatch The reference map result of a
 *     {@link ReferenceCollectingCallback} pass which might be collected from
 *     the whole AST or just a sub-tree associated to a SCRIPT node.
 * @param root AST sub-tree root on which reference collection was done.
 */
void updateGlobalVarReferences(Map<Var, ReferenceCollection>
    refMapPatch, Node root) {
  if (refMap == null || !root.isScript()) {
    resetGlobalVarReferences(refMapPatch);
    return;
  }

  InputId inputId = root.getInputId();
  Preconditions.checkNotNull(inputId);
  // Note there are two assumptions here (i) the order of compiler inputs
  // has not changed and (ii) all references are in the order they appear
  // in AST (this is enforced in ReferenceCollectionCallback).
  removeScriptReferences(inputId);
  for (Entry<Var, ReferenceCollection> entry : refMapPatch.entrySet()) {
    Var var = entry.getKey();
    if (var.isGlobal()) {
      replaceReferences(var.getName(), inputId, entry.getValue());
    }
  }
}
 
Example 3
Source File: Closure_110_ScopedAliases_s.java    From coming with MIT License 6 votes vote down vote up
private SourcePosition<AliasTransformation> getSourceRegion(Node n) {
  Node testNode = n;
  Node next = null;
  for (; next != null || testNode.isScript();) {
    next = testNode.getNext();
    testNode = testNode.getParent();
  }

  int endLine = next == null ? Integer.MAX_VALUE : next.getLineno();
  int endChar = next == null ? Integer.MAX_VALUE : next.getCharno();
  SourcePosition<AliasTransformation> pos =
      new SourcePosition<AliasTransformation>() {};
  pos.setPositionInformation(
      n.getLineno(), n.getCharno(), endLine, endChar);
  return pos;
}
 
Example 4
Source File: LinkCommentsForOneFile.java    From clutz with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (isDone()) {
    return;
  }
  if (n.isScript()) {
    // New dummy node at the end of the file
    Node dummy = new Node(Token.EMPTY);
    n.addChildToBack(dummy);

    while (hasRemainingComments()) {
      // If the new comment is separated from the current one by at least a line,
      // output the current group of comments.
      if (getFirstLineOfNextComment() - getLastLineOfCurrentComment() > 1) {
        dummy.getParent().addChildBefore(newFloatingCommentFromBuffer(), dummy);
      }
      addNextCommentToBuffer();
    }
    n.addChildBefore(newFloatingCommentFromBuffer(), dummy);
    addNextCommentToBuffer();
    n.removeChild(dummy);
  }
}
 
Example 5
Source File: UnreachableCodeElimination.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (parent == null) {
    return;
  }
  if (n.isFunction() || n.isScript()) {
    return;
  }

  DiGraphNode<Node, Branch> gNode = cfg.getDirectedGraphNode(n);
  if (gNode == null) { // Not in CFG.
    return;
  }
  if (gNode.getAnnotation() != GraphReachability.REACHABLE ||
      (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n, compiler))) {
    removeDeadExprStatementSafely(n);
    return;
  }

  tryRemoveUnconditionalBranching(n);
}
 
Example 6
Source File: Closure_17_TypedScopeCreator_s.java    From coming with MIT License 5 votes vote down vote up
@Override
public final boolean shouldTraverse(NodeTraversal t, Node n,
    Node parent) {
  inputId = t.getInputId();
  if (n.isFunction() ||
      n.isScript()) {
    Preconditions.checkNotNull(inputId);
    sourceName = NodeUtil.getSourceName(n);
  }

  // We do want to traverse the name of a named function, but we don't
  // want to traverse the arguments or body.
  boolean descend = parent == null || !parent.isFunction() ||
      n == parent.getFirstChild() || parent == scope.getRootNode();

  if (descend) {
    // Handle hoisted functions on pre-order traversal, so that they
    // get hit before other things in the scope.
    if (NodeUtil.isStatementParent(n)) {
      for (Node child = n.getFirstChild();
           child != null;
           child = child.getNext()) {
        if (NodeUtil.isHoistedFunctionDeclaration(child)) {
          defineFunctionLiteral(child, n);
        }
      }
    }
  }

  return descend;
}
 
Example 7
Source File: Cardumen_00200_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param n The node.
 * @return The InputId property on the node or its ancestors.
 */
public static InputId getInputId(Node n) {
  while (n != null && !n.isScript()) {
    n = n.getParent();
  }

  return (n != null && n.isScript()) ? n.getInputId() : null;
}
 
Example 8
Source File: Cardumen_00200_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * @param n The node.
 * @return The InputId property on the node or its ancestors.
 */
public static InputId getInputId(Node n) {
  while (n != null && !n.isScript()) {
    n = n.getParent();
  }

  return (n != null && n.isScript()) ? n.getInputId() : null;
}
 
Example 9
Source File: Closure_43_TypedScopeCreator_s.java    From coming with MIT License 5 votes vote down vote up
@Override
public final boolean shouldTraverse(NodeTraversal t, Node n,
    Node parent) {
  inputId = t.getInputId();
  if (n.isFunction() ||
      n.isScript()) {
    Preconditions.checkNotNull(inputId);
    sourceName = NodeUtil.getSourceName(n);
  }

  // We do want to traverse the name of a named function, but we don't
  // want to traverse the arguments or body.
  boolean descend = parent == null || !parent.isFunction() ||
      n == parent.getFirstChild() || parent == scope.getRootNode();

  if (descend) {
    // Handle hoisted functions on pre-order traversal, so that they
    // get hit before other things in the scope.
    if (NodeUtil.isStatementParent(n)) {
      for (Node child = n.getFirstChild();
           child != null;
           child = child.getNext()) {
        if (NodeUtil.isHoistedFunctionDeclaration(child)) {
          defineFunctionLiteral(child, n);
        }
      }
    }
  }

  return descend;
}
 
Example 10
Source File: Closure_13_PeepholeOptimizationsPass_t.java    From coming with MIT License 5 votes vote down vote up
private boolean shouldVisit(Node node) {
  if (node.isFunction() || node.isScript()) {
    ScopeState previous = traversalState.peek();
    if (!previous.traverseChildScopes) {
      return false;
    }
    traversalState.push();
  }
  return true;
}
 
Example 11
Source File: Nopol2017_0027_t.java    From coming with MIT License 5 votes vote down vote up
@Override
public final boolean shouldTraverse(NodeTraversal t, Node n,
    Node parent) {
  inputId = t.getInputId();
  if (n.isFunction() ||
      n.isScript()) {
    Preconditions.checkNotNull(inputId);
    sourceName = NodeUtil.getSourceName(n);
  }

  // We do want to traverse the name of a named function, but we don't
  // want to traverse the arguments or body.
  boolean descend = parent == null || !parent.isFunction() ||
      n == parent.getFirstChild() || parent == scope.getRootNode();

  if (descend) {
    // Handle hoisted functions on pre-order traversal, so that they
    // get hit before other things in the scope.
    if (NodeUtil.isStatementParent(n)) {
      for (Node child = n.getFirstChild();
           child != null;
           child = child.getNext()) {
        if (NodeUtil.isHoistedFunctionDeclaration(child)) {
          defineFunctionLiteral(child, n);
        }
      }
    }
  }

  return descend;
}
 
Example 12
Source File: LinkCommentsForOneFile.java    From clutz with MIT License 4 votes vote down vote up
@Override
public final boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) {
  if (isDone()) {
    return false;
  }
  // Ignore top level block
  if (n.isScript() || n.isModuleBody()) {
    return true;
  }

  int line = n.getLineno();
  // Comment is AFTER this line
  if (getLastLineOfCurrentComment() > line) {
    return true;
  }

  boolean outputCommentAfterLine = false;
  while (hasRemainingComments() && !isCommentAdjacentToLine(line)) {
    // Comment is AFTER this line
    if (getLastLineOfCurrentComment() > line) {
      return true;
    }

    // If the new comment is separated from the current one by at least a line,
    // output the current group of comments.
    if (getFirstLineOfNextComment() - getLastLineOfCurrentComment() > 1) {
      outputFloatingCommentFromBuffer(n);
    }
    addNextCommentToBuffer();
    outputCommentAfterLine = true;
  }

  if (getLastLineOfCurrentComment() == line) {
    // Comment on same line as code -- we have to make sure this is the node we should attach
    // it to.
    if (parent.isCall()) {
      // We're inside a function call, we have to be careful about which node to attach to,
      // since comments
      // can go before or after an argument.
      if (linkFunctionArgs(n, line)) return true;
    } else if (getCurrentComment().location.end.column < n.getCharno()) {
      // comment is before this node, so attach it
      linkCommentBufferToNode(n);
    } else {
      return true;
    }
  } else if (getLastLineOfCurrentComment() == line - 1) {
    // Comment ends just before code
    linkCommentBufferToNode(n);
  } else if (!hasRemainingComments() && !outputCommentAfterLine) {
    // Exhausted all comments, output floating comment.
    outputFloatingCommentFromBuffer(n);
  }

  if (!outputCommentAfterLine) {
    addNextCommentToBuffer();
  }
  return true;
}
 
Example 13
Source File: Closure_20_PeepholeSubstituteAlternateSyntax_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Replace duplicate exits in control structures.  If the node following
 * the exit node expression has the same effect as exit node, the node can
 * be replaced or removed.
 * For example:
 *   "while (a) {return f()} return f();" ==> "while (a) {break} return f();"
 *   "while (a) {throw 'ow'} throw 'ow';" ==> "while (a) {break} throw 'ow';"
 *
 * @param n An follow control exit expression (a THROW or RETURN node)
 * @return The replacement for n, or the original if no change was made.
 */
private Node tryReplaceExitWithBreak(Node n) {
  Node result = n.getFirstChild();

  // Find the enclosing control structure, if any, that a "break" would exit
  // from.
  Node breakTarget = n;
  for (;!ControlFlowAnalysis.isBreakTarget(breakTarget, null /* no label */);
      breakTarget = breakTarget.getParent()) {
    if (breakTarget.isFunction() || breakTarget.isScript()) {
      // No break target.
      return n;
    }
  }

  Node follow = ControlFlowAnalysis.computeFollowNode(breakTarget);

  // Skip pass all the finally blocks because both the break and return will
  // also trigger all the finally blocks. However, the order of execution is
  // slightly changed. Consider:
  //
  // return a() -> finally { b() } -> return a()
  //
  // which would call a() first. However, changing the first return to a
  // break will result in calling b().

  Node prefinallyFollows = follow;
  follow = skipFinallyNodes(follow);

  if (prefinallyFollows != follow) {
    // There were finally clauses
    if (!isPure(result)) {
      // Can't defer the exit
      return n;
    }
  }

  if (follow == null && (n.isThrow() || result != null)) {
    // Can't complete remove a throw here or a return with a result.
    return n;
  }

  // When follow is null, this mean the follow of a break target is the
  // end of a function. This means a break is same as return.
  if (follow == null || areMatchingExits(n, follow)) {
    Node replacement = IR.breakNode();
    n.getParent().replaceChild(n, replacement);
    this.reportCodeChange();
    return replacement;
  }

  return n;
}
 
Example 14
Source File: PeepholeCollectPropertyAssignments.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
Node optimizeSubtree(Node subtree) {
  if (!subtree.isScript() && !subtree.isBlock()) {
    return subtree;
  }

  boolean codeChanged = false;

  // Look for variable declarations or simple assignments
  // and start processing there.
  for (Node child = subtree.getFirstChild();
       child != null; child = child.getNext()) {
    if (!child.isVar() && !NodeUtil.isExprAssign(child)) {
      continue;
    }
    if (!isPropertyAssignmentToName(child.getNext())) {
      // Quick check to see if there's anything to collapse.
      continue;
    }

    Preconditions.checkState(child.hasOneChild());
    Node name = getName(child);
    if (!name.isName()) {
      // The assignment target is not a simple name.
      continue;
    }
    Node value = getValue(child);
    if (value == null || !isInterestingValue(value)) {
      // No initializer or not an Object or Array literal.
      continue;
    }

    Node propertyCandidate;
    while ((propertyCandidate = child.getNext()) != null) {
      // This does not infinitely loop because collectProperty always
      // removes propertyCandidate from its parent when it returns true.
      if (!collectProperty(propertyCandidate, name.getString(), value)) {
        break;
      }
      codeChanged = true;
    }
  }

  if (codeChanged) {
    reportCodeChange();
  }
  return subtree;
}
 
Example 15
Source File: Cardumen_0016_t.java    From coming with MIT License 4 votes vote down vote up
private void exitNode(Node node) {
  if (node.isFunction() || node.isScript()) {
    traversalState.pop();
  }
}
 
Example 16
Source File: Nodes.java    From js-dossier with Apache License 2.0 4 votes vote down vote up
public static boolean isScript(@Nullable Node n) {
  return n != null && n.isScript();
}
 
Example 17
Source File: PeepholeOptimizationsPass.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void exitNode(Node node) {
  if (node.isFunction() || node.isScript()) {
    traversalState.pop();
  }
}
 
Example 18
Source File: CollapseProperties.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Updates the initial assignment to a collapsible property at global scope
 * by changing it to a variable declaration (e.g. a.b = 1 -> var a$b = 1).
 * The property's value may either be a primitive or an object literal or
 * function whose properties aren't collapsible.
 *
 * @param alias The flattened property name (e.g. "a$b")
 * @param refName The name for the reference being updated.
 * @param ref An object containing information about the assignment getting
 *     updated
 */
private void updateSimpleDeclaration(String alias, Name refName, Ref ref) {
  Node rvalue = ref.node.getNext();
  Node parent = ref.node.getParent();
  Node gramps = parent.getParent();
  Node greatGramps = gramps.getParent();
  Node greatGreatGramps = greatGramps.getParent();

  if (rvalue != null && rvalue.isFunction()) {
    checkForHosedThisReferences(rvalue, refName.docInfo, refName);
  }

  // Create the new alias node.
  Node nameNode = NodeUtil.newName(
      compiler.getCodingConvention(), alias, gramps.getFirstChild(),
      refName.getFullName());
  NodeUtil.copyNameAnnotations(ref.node.getLastChild(), nameNode);

  if (gramps.isExprResult()) {
    // BEFORE: a.b.c = ...;
    //   exprstmt
    //     assign
    //       getprop
    //         getprop
    //           name a
    //           string b
    //         string c
    //       NODE
    // AFTER: var a$b$c = ...;
    //   var
    //     name a$b$c
    //       NODE

    // Remove the r-value (NODE).
    parent.removeChild(rvalue);
    nameNode.addChildToFront(rvalue);

    Node varNode = IR.var(nameNode);
    greatGramps.replaceChild(gramps, varNode);
  } else {
    // This must be a complex assignment.
    Preconditions.checkNotNull(ref.getTwin());

    // BEFORE:
    // ... (x.y = 3);
    //
    // AFTER:
    // var x$y;
    // ... (x$y = 3);

    Node current = gramps;
    Node currentParent = gramps.getParent();
    for (; !currentParent.isScript() &&
           !currentParent.isBlock();
         current = currentParent,
         currentParent = currentParent.getParent()) {}

    // Create a stub variable declaration right
    // before the current statement.
    Node stubVar = IR.var(nameNode.cloneTree())
        .copyInformationFrom(nameNode);
    currentParent.addChildBefore(stubVar, current);

    parent.replaceChild(ref.node, nameNode);
  }

  compiler.reportCodeChange();
}
 
Example 19
Source File: jKali_003_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node is of a type that contain other statements.
 */
static boolean isStatementBlock(Node n) {
  return n.isScript() || n.isBlock();
}
 
Example 20
Source File: Cardumen_0087_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * @return Whether the node is of a type that contain other statements.
 */
static boolean isStatementBlock(Node n) {
  return n.isScript() || n.isBlock();
}