com.google.javascript.rhino.Token Java Examples

The following examples show how to use com.google.javascript.rhino.Token. 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_94_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 #2
Source File: Closure_61_NodeUtil_t.java    From coming with MIT License 6 votes vote down vote up
static boolean constructorCallHasSideEffects(
    Node callNode, AbstractCompiler compiler) {
  if (callNode.getType() != Token.NEW) {
    throw new IllegalStateException(
        "Expected NEW node, got " + Token.name(callNode.getType()));
  }

  if (callNode.isNoSideEffectsCall()) {
    return false;
  }

  Node nameNode = callNode.getFirstChild();
  if (nameNode.getType() == Token.NAME &&
      CONSTRUCTORS_WITHOUT_SIDE_EFFECTS.contains(nameNode.getString())) {
    return false;
  }

  return true;
}
 
Example #3
Source File: Cardumen_00149_t.java    From coming with MIT License 6 votes vote down vote up
static boolean nodeTypeMayHaveSideEffects(Node n, AbstractCompiler compiler) {
  if (isAssignmentOp(n)) {
    return true;
  }

  switch(n.getType()) {
    case Token.DELPROP:
    case Token.DEC:
    case Token.INC:
    case Token.THROW:
      return true;
    case Token.CALL:
      return NodeUtil.functionCallHasSideEffects(n, compiler);
    case Token.NEW:
      return NodeUtil.constructorCallHasSideEffects(n, compiler);
    case Token.NAME:
      // A variable definition.
      return n.hasChildren();
    default:
      return false;
  }
}
 
Example #4
Source File: Closure_93_ProcessClosurePrimitives_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Processes the output of processed-provide from a previous pass.  This will
 * update our data structures in the same manner as if the provide had been
 * processed in this pass.
 */
private void processProvideFromPreviousPass(
    NodeTraversal t, String name, Node parent) {
  if (!providedNames.containsKey(name)) {
    // Record this provide created on a previous pass, and create a dummy
    // EXPR node as a placeholder to simulate an explicit provide.
    Node expr = new Node(Token.EXPR_RESULT);
    expr.copyInformationFromForTree(parent);
    parent.getParent().addChildBefore(expr, parent);
    compiler.reportCodeChange();

    JSModule module = t.getModule();
    registerAnyProvidedPrefixes(name, expr, module);

    ProvidedName provided = new ProvidedName(name, expr, module, true);
    providedNames.put(name, provided);
    provided.addDefinition(parent, module);
  } else {
    // Remove this provide if it came from a previous pass since we have an
    // replacement already.
    if (isNamespacePlaceholder(parent)) {
      parent.getParent().removeChild(parent);
      compiler.reportCodeChange();
    }
  }
}
 
Example #5
Source File: Closure_87_PeepholeSubstituteAlternateSyntax_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Fold "new Object()" to "Object()".
 */
private Node tryFoldStandardConstructors(Node n) {
  Preconditions.checkState(n.getType() == Token.NEW);

  // If name normalization has been run then we know that
  // new Object() does in fact refer to what we think it is
  // and not some custom-defined Object().
  if (isASTNormalized()) {
    if (n.getFirstChild().getType() == Token.NAME) {
      String className = n.getFirstChild().getString();
      if (STANDARD_OBJECT_CONSTRUCTORS.contains(className)) {
          n.setType(Token.CALL);
          reportCodeChange();
      }
    }
  }

  return n;
}
 
Example #6
Source File: jMutRepair_003_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.isBlock() ||
      addingRoot.isScript());
  Preconditions.checkState(addingRoot.getFirstChild() == null ||
      !addingRoot.getFirstChild().isScript());
  return addingRoot;
}
 
Example #7
Source File: Closure_96_TypeCheck_t.java    From coming with MIT License 6 votes vote down vote up
private void checkNoTypeCheckSection(Node n, boolean enterSection) {
  switch (n.getType()) {
    case Token.SCRIPT:
    case Token.BLOCK:
    case Token.VAR:
    case Token.FUNCTION:
    case Token.ASSIGN:
      JSDocInfo info = n.getJSDocInfo();
      if (info != null && info.isNoTypeCheck()) {
        if (enterSection) {
          noTypeCheckSection++;
        } else {
          noTypeCheckSection--;
        }
      }
      validator.setShouldReport(noTypeCheckSection == 0);
      break;
  }
}
 
Example #8
Source File: Nopol2017_0027_s.java    From coming with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node node, Node parent) {
  Node nameNode = null;
  switch (node.getType()) {
    case Token.VAR:
      for (Node child = node.getFirstChild();
           child != null; child = child.getNext()) {
        identifyNameNode(
            child, child.getFirstChild(),
            NodeUtil.getBestJSDocInfo(child));
      }
      break;
    case Token.EXPR_RESULT:
      Node firstChild = node.getFirstChild();
      if (firstChild.isAssign()) {
        identifyNameNode(
            firstChild.getFirstChild(), firstChild.getLastChild(),
            firstChild.getJSDocInfo());
      } else {
        identifyNameNode(
            firstChild, null, firstChild.getJSDocInfo());
      }
      break;
  }
}
 
Example #9
Source File: Closure_69_TypeCheck_t.java    From coming with MIT License 6 votes vote down vote up
private void checkNoTypeCheckSection(Node n, boolean enterSection) {
  switch (n.getType()) {
    case Token.SCRIPT:
    case Token.BLOCK:
    case Token.VAR:
    case Token.FUNCTION:
    case Token.ASSIGN:
      JSDocInfo info = n.getJSDocInfo();
      if (info != null && info.isNoTypeCheck()) {
        if (enterSection) {
          noTypeCheckSection++;
        } else {
          noTypeCheckSection--;
        }
      }
      validator.setShouldReport(noTypeCheckSection == 0);
      break;
  }
}
 
Example #10
Source File: Closure_75_NodeUtil_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Merge a block with its parent block.
 * @return Whether the block was removed.
 */
static boolean tryMergeBlock(Node block) {
  Preconditions.checkState(block.getType() == Token.BLOCK);
  Node parent = block.getParent();
  // Try to remove the block if its parent is a block/script or if its
  // parent is label and it has exactly one child.
  if (isStatementBlock(parent)) {
    Node previous = block;
    while (block.hasChildren()) {
      Node child = block.removeFirstChild();
      parent.addChildAfter(child, previous);
      previous = child;
    }
    parent.removeChild(block);
    return true;
  } else {
    return false;
  }
}
 
Example #11
Source File: Closure_57_ClosureCodingConvention_s.java    From coming with MIT License 6 votes vote down vote up
@Override
public List<String> identifyTypeDeclarationCall(Node n) {
  Node callName = n.getFirstChild();
  if ("goog.addDependency".equals(callName.getQualifiedName()) &&
      n.getChildCount() >= 3) {
    Node typeArray = callName.getNext().getNext();
    if (typeArray.getType() == Token.ARRAYLIT) {
      List<String> typeNames = Lists.newArrayList();
      for (Node name = typeArray.getFirstChild(); name != null;
           name = name.getNext()) {
        if (name.getType() == Token.STRING) {
          typeNames.add(name.getString());
        }
      }
      return typeNames;
    }
  }
  return null;
}
 
Example #12
Source File: IntegrationTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testAlwaysRunSafetyCheck() {
  CompilerOptions options = createCompilerOptions();
  options.checkSymbols = false;
  options.customPasses = ArrayListMultimap.create();
  options.customPasses.put(
      CustomPassExecutionTime.BEFORE_OPTIMIZATIONS,
      new CompilerPass() {
        @Override public void process(Node externs, Node root) {
          Node var = root.getLastChild().getFirstChild();
          assertEquals(Token.VAR, var.getType());
          var.detachFromParent();
        }
      });
  try {
    test(options,
         "var x = 3; function f() { return x + z; }",
         "function f() { return x + z; }");
    fail("Expected run-time exception");
  } catch (RuntimeException e) {
    assertTrue(e.getMessage().indexOf("Unexpected variable x") != -1);
  }
}
 
Example #13
Source File: 1_NodeUtil.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether a node represents an object literal get or set key
 * (e.g. key1 in {get key1() {}, set key2(a){}).
 *
 * @param node A node
 */
static boolean isGetOrSetKey(Node node) {
  switch (node.getType()) {
    case Token.GET:
    case Token.SET:
      return true;
  }
  return false;
}
 
Example #14
Source File: Closure_68_JsDocInfoParser_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * FieldTypeList := FieldType | FieldType ',' FieldTypeList
 */
private Node parseFieldTypeList(JsDocToken token) {
  Node fieldTypeList = newNode(Token.LB);

  do {
    Node fieldType = parseFieldType(token);

    if (fieldType == null) {
      return null;
    }

    fieldTypeList.addChildToBack(fieldType);

    skipEOLs();
    if (!match(JsDocToken.COMMA)) {
      break;
    }

    // Move to the comma token.
    next();

    // Move to the token passed the comma.
    skipEOLs();
    token = next();
  } while (true);

  return fieldTypeList;
}
 
Example #15
Source File: Closure_54_TypedScopeCreator_t.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 #16
Source File: Closure_59_Compiler_s.java    From coming with MIT License 5 votes vote down vote up
@Override
void updateGlobalVarReferences(Map<Var, ReferenceCollection> refMapPatch,
    Node collectionRoot) {
  Preconditions.checkState(collectionRoot.getType() == Token.SCRIPT
      || collectionRoot.getType() == Token.BLOCK);
  if (globalRefMap == null) {
    globalRefMap = new GlobalVarReferenceMap(getInputsInOrder(),
        getExternsInOrder());
  }
  globalRefMap.updateGlobalVarReferences(refMapPatch, collectionRoot);
}
 
Example #17
Source File: Closure_65_CodeGenerator_s.java    From coming with MIT License 5 votes vote down vote up
/** Gets the first non-empty child of the given node. */
private static Node getFirstNonEmptyChild(Node n) {
  for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
    if (c.getType() == Token.BLOCK) {
      Node result = getFirstNonEmptyChild(c);
      if (result != null) {
        return result;
      }
    } else if (c.getType() != Token.EMPTY) {
      return c;
    }
  }
  return null;
}
 
Example #18
Source File: Closure_100_CheckGlobalThis_t.java    From coming with MIT License 5 votes vote down vote up
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.getType() == Token.THIS && shouldReportThis(n, parent)) {
    compiler.report(t.makeError(n, level, GLOBAL_THIS));
  }
  if (n == assignLhsChild) {
    assignLhsChild = null;
  }
}
 
Example #19
Source File: Closure_37_IRFactory_t.java    From coming with MIT License 5 votes vote down vote up
@Override
Node processIfStatement(IfStatement statementNode) {
  Node node = newNode(Token.IF);
  node.addChildToBack(transform(statementNode.getCondition()));
  node.addChildToBack(transformBlock(statementNode.getThenPart()));
  if (statementNode.getElsePart() != null) {
    node.addChildToBack(transformBlock(statementNode.getElsePart()));
  }
  return node;
}
 
Example #20
Source File: Cardumen_00202_s.java    From coming with MIT License 5 votes vote down vote up
@Override
public void remove() {
  // Setters have VAR, FUNCTION, or ASSIGN parent nodes. CALL parent
  // nodes are global refs, and are handled later in this function.
  Node containingNode = parent.getParent();
  switch (parent.getType()) {
    case Token.VAR:
      Preconditions.checkState(parent.hasOneChild());
      replaceWithRhs(containingNode, parent);
      break;
    case Token.FUNCTION:
      replaceWithRhs(containingNode, parent);
      break;
    case Token.ASSIGN:
      if (containingNode.isExprResult()) {
        replaceWithRhs(containingNode.getParent(), containingNode);
      } else {
        replaceWithRhs(containingNode, parent);
      }
      break;
    case Token.OBJECTLIT:
      // TODO(nicksantos): Come up with a way to remove this.
      // If we remove object lit keys, then we will need to also
      // create dependency scopes for them.
      break;
  }
}
 
Example #21
Source File: Closure_95_TypedScopeCreator_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Handle typedefs.
 * @param t The current traversal.
 * @param candidate A qualified name node.
 * @param info JSDoc comments.
 */
private void checkForTypedef(
    NodeTraversal t, Node candidate, JSDocInfo info) {
  if (info == null || !info.hasTypedefType()) {
    return;
  }

  String typedef = candidate.getQualifiedName();
  if (typedef == null) {
    return;
  }

  // TODO(nicksantos|user): This is a terrible, terrible hack
  // to bail out on recusive typedefs. We'll eventually need
  // to handle these properly.
  typeRegistry.forwardDeclareType(typedef);

  JSType realType = info.getTypedefType().evaluate(scope, typeRegistry);
  if (realType == null) {
    compiler.report(
        JSError.make(
            t.getSourceName(), candidate, MALFORMED_TYPEDEF, typedef));
  }

  typeRegistry.declareType(typedef, realType);
  if (candidate.getType() == Token.GETPROP) {
    defineSlot(candidate, candidate.getParent(),
        getNativeType(NO_TYPE), false);
  }
}
 
Example #22
Source File: Closure_80_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
static int getOpFromAssignmentOp(Node n) {
  switch (n.getType()){
    case Token.ASSIGN_BITOR:
      return Token.BITOR;
    case Token.ASSIGN_BITXOR:
      return Token.BITXOR;
    case Token.ASSIGN_BITAND:
      return Token.BITAND;
    case Token.ASSIGN_LSH:
      return Token.LSH;
    case Token.ASSIGN_RSH:
      return Token.RSH;
    case Token.ASSIGN_URSH:
      return Token.URSH;
    case Token.ASSIGN_ADD:
      return Token.ADD;
    case Token.ASSIGN_SUB:
      return Token.SUB;
    case Token.ASSIGN_MUL:
      return Token.MUL;
    case Token.ASSIGN_DIV:
      return Token.DIV;
    case Token.ASSIGN_MOD:
      return Token.MOD;
  }
  throw new IllegalArgumentException("Not an assiment op");
}
 
Example #23
Source File: Closure_37_IRFactory_t.java    From coming with MIT License 5 votes vote down vote up
@Override
Node processBreakStatement(BreakStatement statementNode) {
  Node node = newNode(Token.BREAK);
  if (statementNode.getBreakLabel() != null) {
    Node labelName = transform(statementNode.getBreakLabel());
    // Change the NAME to LABEL_NAME
    labelName.setType(Token.LABEL_NAME);
    node.addChildToBack(labelName);
  }
  return node;
}
 
Example #24
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 #25
Source File: Closure_19_ChainableReverseAbstractInterpreter_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns the type of a node in the given scope if the node corresponds to a
 * name whose type is capable of being refined.
 * @return The current type of the node if it can be refined, null otherwise.
 */
protected JSType getTypeIfRefinable(Node node, FlowScope scope) {
  switch (node.getType()) {
    case Token.NAME:
      StaticSlot<JSType> nameVar = scope.getSlot(node.getString());
      if (nameVar != null) {
        JSType nameVarType = nameVar.getType();
        if (nameVarType == null) {
          nameVarType = node.getJSType();
        }
        return nameVarType;
      }
      return null;

    case Token.GETPROP:
      String qualifiedName = node.getQualifiedName();
      if (qualifiedName == null) {
        return null;
      }
      StaticSlot<JSType> propVar = scope.getSlot(qualifiedName);
      JSType propVarType = null;
      if (propVar != null) {
        propVarType = propVar.getType();
      }
      if (propVarType == null) {
        propVarType = node.getJSType();
      }
      if (propVarType == null) {
        propVarType = getNativeType(UNKNOWN_TYPE);
      }
      return propVarType;
  }
  return null;
}
 
Example #26
Source File: Closure_61_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Converts an operator's token value (see {@link Token}) to a string
 * representation or fails.
 *
 * @param operator the operator's token value to convert
 * @return the string representation
 * @throws Error if the token value is not an operator
 */
static String opToStrNoFail(int operator) {
  String res = opToStr(operator);
  if (res == null) {
    throw new Error("Unknown op " + operator + ": " +
                    Token.name(operator));
  }
  return res;
}
 
Example #27
Source File: Closure_133_JsDocInfoParser_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * ArrayType := '[' ElementTypeList ']'
 * ElementTypeList := <empty> | TypeExpression | '...' TypeExpression
 *     | TypeExpression ',' ElementTypeList
 */
private Node parseArrayType(JsDocToken token) {
  Node array = newNode(Token.LB);
  Node arg = null;
  boolean hasVarArgs = false;

  do {
    if (arg != null) {
      next();
      skipEOLs();
      token = next();
    }
    if (token == JsDocToken.ELLIPSIS) {
      arg = wrapNode(Token.ELLIPSIS, parseTypeExpression(next()));
      hasVarArgs = true;
    } else {
      arg = parseTypeExpression(token);
    }

    if (arg == null) {
      return null;
    }

    array.addChildToBack(arg);
    if (hasVarArgs) {
      break;
    }
    skipEOLs();
  } while (match(JsDocToken.COMMA));

  if (!match(JsDocToken.RB)) {
    return reportTypeSyntaxWarning("msg.jsdoc.missing.rb");
  }
  next();
  return array;
}
 
Example #28
Source File: Closure_75_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Determines whether a node represents an object literal get or set key
 * (e.g. key1 in {get key1() {}, set key2(a){}).
 *
 * @param node A node
 */
static boolean isGetOrSetKey(Node node) {
  switch (node.getType()) {
    case Token.GET:
    case Token.SET:
      return true;
  }
  return false;
}
 
Example #29
Source File: Closure_86_NodeUtil_t.java    From coming with MIT License 5 votes vote down vote up
public boolean apply(Node n) {
  Node parent = n.getParent();
  return n.getType() == Token.BLOCK
      || (!isFunction(n) && (parent == null
          || isControlStructure(parent)
          || isStatementBlock(parent)));
}
 
Example #30
Source File: Closure_80_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Determines whether the given node is a FOR, DO, or WHILE node.
 */
static boolean isLoopStructure(Node n) {
  switch (n.getType()) {
    case Token.FOR:
    case Token.DO:
    case Token.WHILE:
      return true;
    default:
      return false;
  }
}