Java Code Examples for com.google.javascript.rhino.Token#VAR

The following examples show how to use com.google.javascript.rhino.Token#VAR . 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_92_ProcessClosurePrimitives_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * @return Whether the node is namespace placeholder.
 */
private static boolean isNamespacePlaceholder(Node n) {
  if (!n.getBooleanProp(Node.IS_NAMESPACE)) {
    return false;
  }

  Node value = null;
  if (n.getType() == Token.EXPR_RESULT) {
    Node assign = n.getFirstChild();
    value = assign.getLastChild();
  } else if (n.getType() == Token.VAR) {
    Node name = n.getFirstChild();
    value = name.getFirstChild();
  }

  return value != null
    && value.getType() == Token.OBJECTLIT
    && !value.hasChildren();
}
 
Example 2
Source File: Nopol2017_0051_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 3
Source File: Closure_86_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 4
Source File: Closure_71_CheckAccessControls_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Checks the given NAME node to ensure that access restrictions are obeyed.
 */
private void checkNameDeprecation(NodeTraversal t, Node n, Node parent) {
  // Don't bother checking definitions or constructors.
  if (parent.getType() == Token.FUNCTION || parent.getType() == Token.VAR ||
      parent.getType() == Token.NEW) {
    return;
  }

  Scope.Var var = t.getScope().getVar(n.getString());
  JSDocInfo docInfo = var == null ? null : var.getJSDocInfo();

  if (docInfo != null && docInfo.isDeprecated() &&
      shouldEmitDeprecationWarning(t, n, parent)) {

    if (docInfo.getDeprecationReason() != null) {
      compiler.report(
          t.makeError(n, DEPRECATED_NAME_REASON, n.getString(),
              docInfo.getDeprecationReason()));
    } else {
      compiler.report(
          t.makeError(n, DEPRECATED_NAME, n.getString()));
    }
  }
}
 
Example 5
Source File: Nopol2017_0027_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Visit a node in the global scope, and add anything it declares to the
 * global symbol table.
 *
 * @param t The current traversal.
 * @param n The node being visited.
 * @param parent The parent of n
 */
@Override public void visit(NodeTraversal t, Node n, Node parent) {
  super.visit(t, n, parent);

  switch (n.getType()) {

    case Token.VAR:
      // Handle typedefs.
      if (n.hasOneChild()) {
        checkForTypedef(t, n.getFirstChild(), n.getJSDocInfo());
      }
      break;
  }
}
 
Example 6
Source File: Closure_17_TypedScopeCreator_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Visit a node in the global scope, and add anything it declares to the
 * global symbol table.
 *
 * @param t The current traversal.
 * @param n The node being visited.
 * @param parent The parent of n
 */
@Override public void visit(NodeTraversal t, Node n, Node parent) {
  super.visit(t, n, parent);

  switch (n.getType()) {

    case Token.VAR:
      // Handle typedefs.
      if (n.hasOneChild()) {
        checkForTypedef(t, n.getFirstChild(), n.getJSDocInfo());
      }
      break;
  }
}
 
Example 7
Source File: Closure_86_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
public void visit(Node n) {
  if (n.getType() == Token.NAME) {
    Node parent = n.getParent();
    if (parent != null && parent.getType() == Token.VAR) {
      String name = n.getString();
      if (!vars.containsKey(name)) {
        vars.put(name, n);
      }
    }
  }
}
 
Example 8
Source File: jMutRepair_003_s.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 9
Source File: Closure_105_FoldConstants_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * @return Whether the node is a block with a single statement that is
 *     a VAR declaration of a single variable.
 */
private boolean isVarBlock(Node n) {
  if (n.getType() == Token.BLOCK) {
    if (n.hasOneChild()) {
      Node first = n.getFirstChild();
      if (first.getType() == Token.VAR) {
        return first.hasOneChild();
      }
    }
  }

  return false;
}
 
Example 10
Source File: MaybeReachingVariableUse.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void computeMayUse(
    Node n, Node cfgNode, ReachingUses output, boolean conditional) {
  switch (n.getType()) {

    case Token.BLOCK:
    case Token.FUNCTION:
      return;

    case Token.NAME:
      addToUseIfLocal(n.getString(), cfgNode, output);
      return;

    case Token.WHILE:
    case Token.DO:
    case Token.IF:
      computeMayUse(
          NodeUtil.getConditionExpression(n), cfgNode, output, conditional);
      return;

    case Token.FOR:
      if (!NodeUtil.isForIn(n)) {
        computeMayUse(
            NodeUtil.getConditionExpression(n), cfgNode, output, conditional);
      } else {
        // for(x in y) {...}
        Node lhs = n.getFirstChild();
        Node rhs = lhs.getNext();
        if (lhs.isVar()) {
          lhs = lhs.getLastChild(); // for(var x in y) {...}
        }
        if (lhs.isName() && !conditional) {
          removeFromUseIfLocal(lhs.getString(), output);
        }
        computeMayUse(rhs, cfgNode, output, conditional);
      }
      return;

    case Token.AND:
    case Token.OR:
      computeMayUse(n.getLastChild(), cfgNode, output, true);
      computeMayUse(n.getFirstChild(), cfgNode, output, conditional);
      return;

    case Token.HOOK:
      computeMayUse(n.getLastChild(), cfgNode, output, true);
      computeMayUse(n.getFirstChild().getNext(), cfgNode, output, true);
      computeMayUse(n.getFirstChild(), cfgNode, output, conditional);
      return;

    case Token.VAR:
      Node varName = n.getFirstChild();
      Preconditions.checkState(n.hasChildren(), "AST should be normalized");

      if (varName.hasChildren()) {
        computeMayUse(varName.getFirstChild(), cfgNode, output, conditional);
        if (!conditional) {
          removeFromUseIfLocal(varName.getString(), output);
        }
      }
      return;

    default:
      if (NodeUtil.isAssignmentOp(n) && n.getFirstChild().isName()) {
        Node name = n.getFirstChild();
        if (!conditional) {
          removeFromUseIfLocal(name.getString(), output);
        }

        // In case of a += "Hello". There is a read of a.
        if (!n.isAssign()) {
          addToUseIfLocal(name.getString(), cfgNode, output);
        }

        computeMayUse(name.getNext(), cfgNode, output, conditional);
      } else {
        /*
         * We want to traverse in reverse order because we want the LAST
         * definition in the sub-tree....
         * But we have no better way to traverse in reverse other :'(
         */
        for (Node c = n.getLastChild(); c != null; c = n.getChildBefore(c)) {
          computeMayUse(c, cfgNode, output, conditional);
        }
      }
  }
}
 
Example 11
Source File: Closure_95_TypedScopeCreator_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Defines a typed variable. The defining node will be annotated with the
 * variable's type of {@link JSTypeNative#UNKNOWN_TYPE} if its type is
 * inferred.
 *
 * Slots may be any variable or any qualified name in the global scope.
 *
 * @param n the defining NAME or GETPROP node.
 * @param parent the {@code n}'s parent.
 * @param type the variable's type. It may be {@code null} if
 *     {@code inferred} is {@code true}.
 */
void defineSlot(Node n, Node parent, JSType type, boolean inferred) {
  Preconditions.checkArgument(inferred || type != null);

  // Only allow declarations of NAMEs and qualfied names.
  boolean shouldDeclareOnGlobalThis = false;
  if (n.getType() == Token.NAME) {
    Preconditions.checkArgument(
        parent.getType() == Token.FUNCTION ||
        parent.getType() == Token.VAR ||
        parent.getType() == Token.LP ||
        parent.getType() == Token.CATCH);
    shouldDeclareOnGlobalThis = scope.isGlobal() &&
        (parent.getType() == Token.VAR ||
         parent.getType() == Token.FUNCTION);
  } else {
    Preconditions.checkArgument(
        n.getType() == Token.GETPROP &&
        (parent.getType() == Token.ASSIGN ||
         parent.getType() == Token.EXPR_RESULT));
  }
  String variableName = n.getQualifiedName();
  Preconditions.checkArgument(!variableName.isEmpty());

  // If n is a property, then we should really declare it in the
  // scope where the root object appears. This helps out people
  // who declare "global" names in an anonymous namespace.
  Scope scopeToDeclareIn = scope;

    // don't try to declare in the global scope if there's
    // already a symbol there with this name.

  // declared in closest scope?
  if (scopeToDeclareIn.isDeclared(variableName, false)) {
    Var oldVar = scopeToDeclareIn.getVar(variableName);
    validator.expectUndeclaredVariable(
        sourceName, n, parent, oldVar, variableName, type);
  } else {
    if (!inferred) {
      setDeferredType(n, type);
    }
    CompilerInput input = compiler.getInput(sourceName);
    scopeToDeclareIn.declare(variableName, n, type, input, inferred);

    if (shouldDeclareOnGlobalThis) {
      ObjectType globalThis =
          typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS);
      boolean isExtern = input.isExtern();
      if (inferred) {
        globalThis.defineInferredProperty(variableName,
            type == null ?
                getNativeType(JSTypeNative.NO_TYPE) :
                type,
            isExtern);
      } else {
        globalThis.defineDeclaredProperty(variableName, type, isExtern);
      }
    }

    // If we're in the global scope, also declare var.prototype
    // in the scope chain.
    if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) {
      FunctionType fnType = (FunctionType) type;
      if (fnType.isConstructor() || fnType.isInterface()) {
        FunctionType superClassCtor = fnType.getSuperClassConstructor();
        scopeToDeclareIn.declare(variableName + ".prototype", n,
            fnType.getPrototype(), compiler.getInput(sourceName),
            /* declared iff there's an explicit supertype */
            superClassCtor == null ||
            superClassCtor.getInstanceType().equals(
                getNativeType(OBJECT_TYPE)));
      }
    }
  }
}
 
Example 12
Source File: Closure_106_GlobalNamespace_s.java    From coming with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void visit(NodeTraversal t, Node n, Node parent) {
  if (nodeFilter != null && !nodeFilter.apply(n)) {
    return;
  }

  // If we are traversing the externs, then we save a pointer to the scope
  // generated by them, so that we can do lookups in it later.
  if (externsRoot != null && n == externsRoot) {
    externsScope = t.getScope();
  }

  String name;
  boolean isSet = false;
  Name.Type type = Name.Type.OTHER;
  boolean isPropAssign = false;

  switch (n.getType()) {
    case Token.STRING:
      // This may be a key in an object literal declaration.
      name = null;
      if (parent != null && parent.getType() == Token.OBJECTLIT) {
        name = getNameForObjLitKey(n);
      }
      if (name == null) return;
      isSet = true;
      type = getValueType(n.getNext());
      break;
    case Token.NAME:
      // This may be a variable get or set.
      if (parent != null) {
        switch (parent.getType()) {
          case Token.VAR:
            isSet = true;
            Node rvalue = n.getFirstChild();
            type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue);
            break;
          case Token.ASSIGN:
            if (parent.getFirstChild() == n) {
              isSet = true;
              type = getValueType(n.getNext());
            }
            break;
          case Token.GETPROP:
            return;
          case Token.FUNCTION:
            Node gramps = parent.getParent();
            if (gramps == null ||
                NodeUtil.isFunctionAnonymous(parent)) return;
            isSet = true;
            type = Name.Type.FUNCTION;
            break;
        }
      }
      name = n.getString();
      break;
    case Token.GETPROP:
      // This may be a namespaced name get or set.
      if (parent != null) {
        switch (parent.getType()) {
          case Token.ASSIGN:
            if (parent.getFirstChild() == n) {
              isSet = true;
              type = getValueType(n.getNext());
              isPropAssign = true;
            }
            break;
          case Token.GETPROP:
            return;
        }
      }
      name = n.getQualifiedName();
      if (name == null) return;
      break;
    default:
      return;
  }

  // We are only interested in global names.
  Scope scope = t.getScope();
  if (!isGlobalNameReference(name, scope)) {
    return;
  }

  if (isSet) {
    if (isGlobalScope(scope)) {
      handleSetFromGlobal(t, n, parent, name, isPropAssign, type);
    } else {
      handleSetFromLocal(t, n, parent, name);
    }
  } else {
    handleGet(t, n, parent, name);
  }
}
 
Example 13
Source File: Closure_75_NodeUtil_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Is this a VAR node?
 */
static boolean isVar(Node n) {
  return n.getType() == Token.VAR;
}
 
Example 14
Source File: Closure_114_NameAnalyzer_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Simplify a toplevel expression, while preserving program
 * behavior.
 */
private void replaceTopLevelExpressionWithRhs(Node parent, Node n) {
  // validate inputs
  switch (parent.getType()) {
    case Token.BLOCK:
    case Token.SCRIPT:
    case Token.FOR:
    case Token.LABEL:
      break;
    default:
      throw new IllegalArgumentException(
          "Unsupported parent node type in replaceWithRhs " +
          Token.name(parent.getType()));
  }

  switch (n.getType()) {
    case Token.EXPR_RESULT:
    case Token.FUNCTION:
    case Token.VAR:
      break;
    case Token.ASSIGN:
      Preconditions.checkArgument(parent.isFor(),
          "Unsupported assignment in replaceWithRhs. parent: %s",
          Token.name(parent.getType()));
      break;
    default:
      throw new IllegalArgumentException(
          "Unsupported node type in replaceWithRhs " +
          Token.name(n.getType()));
  }

  // gather replacements
  List<Node> replacements = Lists.newArrayList();
  for (Node rhs : getRhsSubexpressions(n)) {
    replacements.addAll(getSideEffectNodes(rhs));
  }

  if (parent.isFor()) {
    // tweak replacements array s.t. it is a single expression node.
    if (replacements.isEmpty()) {
      replacements.add(IR.empty());
    } else {
      Node expr = collapseReplacements(replacements);
      replacements.clear();
      replacements.add(expr);
    }
  }

  changeProxy.replaceWith(parent, n, replacements);
}
 
Example 15
Source File: Closure_70_TypedScopeCreator_s.java    From coming with MIT License 4 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  attachLiteralTypes(t, n);

  switch (n.getType()) {
    case Token.CALL:
      checkForClassDefiningCalls(t, n, parent);
      break;

    case Token.FUNCTION:
      if (t.getInput() == null || !t.getInput().isExtern()) {
        nonExternFunctions.add(n);
      }

      // Hoisted functions are handled during pre-traversal.
      if (!NodeUtil.isHoistedFunctionDeclaration(n)) {
        defineFunctionLiteral(n, parent);
      }
      break;

    case Token.ASSIGN:
      // Handle initialization of properties.
      Node firstChild = n.getFirstChild();
      if (firstChild.getType() == Token.GETPROP &&
          firstChild.isQualifiedName()) {
        maybeDeclareQualifiedName(t, n.getJSDocInfo(),
            firstChild, n, firstChild.getNext());
      }
      break;

    case Token.CATCH:
      defineCatch(n, parent);
      break;

    case Token.VAR:
      defineVar(n, parent);
      break;

    case Token.GETPROP:
      // Handle stubbed properties.
      if (parent.getType() == Token.EXPR_RESULT &&
          n.isQualifiedName()) {
        maybeDeclareQualifiedName(t, n.getJSDocInfo(), n, parent, null);
      }
      break;
  }
}
 
Example 16
Source File: Closure_130_CollapseProperties_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Updates the first initialization (a.k.a "declaration") of a global name
 * that occurs at an ASSIGN node. See comment for
 * {@link #updateObjLitOrFunctionDeclaration}.
 *
 * @param n An object representing a global name (e.g. "a", "a.b.c")
 * @param alias The flattened name for {@code n} (e.g. "a", "a$b$c")
 */
private void updateObjLitOrFunctionDeclarationAtAssignNode(
    Name n, String alias, boolean canCollapseChildNames) {
  // NOTE: It's important that we don't add additional nodes
  // (e.g. a var node before the exprstmt) because the exprstmt might be
  // the child of an if statement that's not inside a block).

  Ref ref = n.getDeclaration();
  Node rvalue = ref.node.getNext();
  Node varNode = new Node(Token.VAR);
  Node varParent = ref.node.getAncestor(3);
  Node gramps = ref.node.getAncestor(2);
  boolean isObjLit = rvalue.isObjectLit();
  boolean insertedVarNode = false;

  if (isObjLit && n.canEliminate()) {
    // Eliminate the object literal altogether.
    varParent.replaceChild(gramps, varNode);
    ref.node = null;
    insertedVarNode = true;

  } else if (!n.isSimpleName()) {
    // Create a VAR node to declare the name.
    if (rvalue.isFunction()) {
      checkForHosedThisReferences(rvalue, n.docInfo, n);
    }

    ref.node.getParent().removeChild(rvalue);

    Node nameNode = NodeUtil.newName(
        compiler.getCodingConvention(),
        alias, ref.node.getAncestor(2), n.getFullName());

    JSDocInfo info = ref.node.getParent().getJSDocInfo();
    if (ref.node.getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME) ||
        (info != null && info.isConstant())) {
      nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }

    if (info != null) {
      varNode.setJSDocInfo(info);
    }
    varNode.addChildToBack(nameNode);
    nameNode.addChildToFront(rvalue);
    varParent.replaceChild(gramps, varNode);

    // Update the node ancestry stored in the reference.
    ref.node = nameNode;
    insertedVarNode = true;
  }

  if (canCollapseChildNames) {
    if (isObjLit) {
      declareVarsForObjLitValues(
          n, alias, rvalue,
          varNode, varParent.getChildBefore(varNode), varParent);
    }

    addStubsForUndeclaredProperties(n, alias, varParent, varNode);
  }

  if (insertedVarNode) {
    if (!varNode.hasChildren()) {
      varParent.removeChild(varNode);
    }
    compiler.reportCodeChange();
  }
}
 
Example 17
Source File: Closure_80_NodeUtil_s.java    From coming with MIT License 4 votes vote down vote up
public boolean apply(Node n) {
  return isFunctionDeclaration(n) || n.getType() == Token.VAR;
}
 
Example 18
Source File: Closure_106_GlobalNamespace_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Determines whether the result of a hook (x?y:z) or boolean expression
 * (x||y) or (x&&y) is assigned to a specific global name.
 *
 * @param t The traversal
 * @param parent The parent of the current node in the traversal. This node
 *     should already be known to be a HOOK, AND, or OR node.
 * @param name A name that is already known to be global in the current
 *     scope (e.g. "a" or "a.b.c.d")
 * @return The expression's get type, either {@link Ref.Type#DIRECT_GET} or
 *     {@link Ref.Type#ALIASING_GET}
 */
Ref.Type determineGetTypeForHookOrBooleanExpr(
    NodeTraversal t, Node parent, String name) {
  Node prev = parent;
  for (Node anc : parent.getAncestors()) {
    switch (anc.getType()) {
      case Token.EXPR_RESULT:
      case Token.VAR:
      case Token.IF:
      case Token.WHILE:
      case Token.FOR:
      case Token.TYPEOF:
      case Token.VOID:
      case Token.NOT:
      case Token.BITNOT:
      case Token.POS:
      case Token.NEG:
        return Ref.Type.DIRECT_GET;
      case Token.HOOK:
        if (anc.getFirstChild() == prev) {
          return Ref.Type.DIRECT_GET;
        }
        break;
      case Token.ASSIGN:
        if (!name.equals(anc.getFirstChild().getQualifiedName())) {
          return Ref.Type.ALIASING_GET;
        }
        break;
      case Token.NAME:  // a variable declaration
        if (!name.equals(anc.getString())) {
          return Ref.Type.ALIASING_GET;
        }
        break;
      case Token.CALL:
        if (anc.getFirstChild() != prev) {
          return Ref.Type.ALIASING_GET;
        }
        break;
    }
    prev = anc;
  }
  return Ref.Type.ALIASING_GET;
}
 
Example 19
Source File: Closure_60_NodeUtil_t.java    From coming with MIT License 2 votes vote down vote up
/**
 * Is this node the name of a variable being declared?
 *
 * @param n The node
 * @return True if {@code n} is NAME and {@code parent} is VAR
 */
static boolean isVarDeclaration(Node n) {
  // There is no need to verify that parent != null because a NAME node
  // always has a parent in a valid parse tree.
  return n.getType() == Token.NAME && n.getParent().getType() == Token.VAR;
}
 
Example 20
Source File: Closure_94_NodeUtil_s.java    From coming with MIT License 2 votes vote down vote up
/**
 * Determines whether this node is strictly on the left hand side of an assign
 * or var initialization. Notably, this does not include all L-values, only
 * statements where the node is used only as an L-value.
 *
 * @param n The node
 * @param parent Parent of the node
 * @return True if n is the left hand of an assign
 */
static boolean isLhs(Node n, Node parent) {
  return (parent.getType() == Token.ASSIGN && parent.getFirstChild() == n) ||
         parent.getType() == Token.VAR;
}