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

The following examples show how to use com.google.javascript.rhino.Node#isName() . 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_36_InlineVariables_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * If any of the variables are well-defined and alias other variables,
 * mark them as aliasing candidates.
 */
private void collectAliasCandidates(NodeTraversal t,
    ReferenceMap referenceMap) {
  if (mode != Mode.CONSTANTS_ONLY) {
    for (Iterator<Var> it = t.getScope().getVars(); it.hasNext();) {
      Var v = it.next();
      ReferenceCollection referenceInfo = referenceMap.getReferences(v);

      // NOTE(nicksantos): Don't handle variables that are never used.
      // The tests are much easier to write if you don't, and there's
      // another pass that handles unused variables much more elegantly.
      if (referenceInfo != null && referenceInfo.references.size() >= 2 &&
          referenceInfo.isWellDefined() &&
          referenceInfo.isAssignedOnceInLifetime()) {
        Reference init = referenceInfo.getInitializingReference();
        Node value = init.getAssignedValue();
        if (value != null && value.isName()) {
          aliasCandidates.put(value, new AliasCandidate(v, referenceInfo));
        }
      }
    }
  }
}
 
Example 2
Source File: ClosureReverseAbstractInterpreter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public FlowScope getPreciserScopeKnowingConditionOutcome(Node condition,
    FlowScope blindScope, boolean outcome) {
  if (condition.isCall() && condition.getChildCount() == 2) {
    Node callee = condition.getFirstChild();
    Node param = condition.getLastChild();
    if (callee.isGetProp() && param.isQualifiedName()) {
      JSType paramType =  getTypeIfRefinable(param, blindScope);
      Node left = callee.getFirstChild();
      Node right = callee.getLastChild();
      if (left.isName() && "goog".equals(left.getString()) &&
          right.isString()) {
        Function<TypeRestriction, JSType> restricter =
            restricters.get(right.getString());
        if (restricter != null) {
          return restrictParameter(param, paramType, blindScope, restricter,
              outcome);
        }
      }
    }
  }
  return nextPreciserScopeKnowingConditionOutcome(
      condition, blindScope, outcome);
}
 
Example 3
Source File: FunctionArgumentInjector.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check for uses of the named value that imply a pass-by-value
 * parameter is expected.  This is used to prevent cases like:
 *
 *   function (x) {
 *     x=2;
 *     return x;
 *   }
 *
 * We don't want "undefined" to be substituted for "x", and get
 *   undefined=2
 *
 * @param n The node in question.
 * @param parent The parent of the node.
 * @param names The set of names to check.
 * @param unsafe The set of names that require aliases.
 * @param inInnerFunction Whether the inspection is occurring on a inner
 *     function.
 */
private static Set<String> findModifiedParameters(
    Node n, Node parent, Set<String> names, Set<String> unsafe,
    boolean inInnerFunction) {
  Preconditions.checkArgument(unsafe != null);
  if (n.isName()) {
    if (names.contains(n.getString())) {
      if (inInnerFunction || canNameValueChange(n, parent)) {
        unsafe.add(n.getString());
      }
    }
  } else if (n.isFunction()) {
    // A function parameter can not be replaced with a direct inlined value
    // if it is referred to by an inner function. The inner function
    // can out live the call we are replacing, so inner function must
    // capture a unique name.  This approach does not work within loop
    // bodies so those are forbidden elsewhere.
    inInnerFunction = true;
  }

  for (Node c : n.children()) {
    findModifiedParameters(c, n, names, unsafe, inInnerFunction);
  }

  return unsafe;
}
 
Example 4
Source File: Closure_132_PeepholeSubstituteAlternateSyntax_t.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 && value.getNext() == null &&
        NodeUtil.isImmutableValue(value)) {
      Node addition = IR.add(
          IR.string("").srcref(callTarget),
          value.detachFromParent());
      n.getParent().replaceChild(n, addition);
      reportCodeChange();
      return addition;
    }
  }
  return n;
}
 
Example 5
Source File: Closure_43_TypedScopeCreator_s.java    From coming with MIT License 6 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.
  // Object literal keys will have to compute their names themselves.
  if (n.isName()) {
    Preconditions.checkArgument(
        parent.isFunction() ||
        parent.isVar() ||
        parent.isParamList() ||
        parent.isCatch());
  } else {
    Preconditions.checkArgument(
        n.isGetProp() &&
        (parent.isAssign() ||
         parent.isExprResult()));
  }
  defineSlot(n, parent, n.getQualifiedName(), type, inferred);
}
 
Example 6
Source File: jMutRepair_005_s.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 7
Source File: SideEffectsAnalysis.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Calculates the MOD/REF summary for the given node.
 */
@Override
LocationSummary calculateLocationSummary(Node node) {
  int visibilityRefLocations = VISIBILITY_LOCATION_NONE;
  int visibilityModLocations = VISIBILITY_LOCATION_NONE;

  for (Node reference : findStorageLocationReferences(node)) {
    int effectMask;

    if (reference.isName()) {
      // Variable access
      effectMask = effectMaskForVariableReference(reference);
     } else {
      // Heap access
      effectMask = HEAP_LOCATION_MASK;
    }

    if (storageNodeIsLValue(reference)) {
      visibilityModLocations |= effectMask;
    }

    if (storageNodeIsRValue(reference)) {
      visibilityRefLocations |= effectMask;
    }
  }

  VisibilityBasedEffectLocation modSet =
      new VisibilityBasedEffectLocation(visibilityModLocations);

  VisibilityBasedEffectLocation refSet =
    new VisibilityBasedEffectLocation(visibilityRefLocations);

  return new LocationSummary(modSet, refSet);
}
 
Example 8
Source File: Cardumen_0014_t.java    From coming with MIT License 5 votes vote down vote up
/** Find the best JSDoc for the given node. */
static JSDocInfo getBestJSDocInfo(Node n) {
  JSDocInfo info = n.getJSDocInfo();
  if (info == null) {
    Node parent = n.getParent();
    if (parent == null) {
      return null;
    }

    if (parent.isName()) {
      return getBestJSDocInfo(parent);
    } else if (parent.isAssign()) {
      return parent.getJSDocInfo();
    } else if (isObjectLitKey(parent, parent.getParent())) {
      return parent.getJSDocInfo();
    } else if (parent.isFunction()) {
      return parent.getJSDocInfo();
    } else if (parent.isVar() && parent.hasOneChild()) {
      return parent.getJSDocInfo();
    } else if ((parent.isHook() && parent.getFirstChild() != n) ||
               parent.isOr() ||
               parent.isAnd() ||
               (parent.isComma() && parent.getFirstChild() != n)) {
      return getBestJSDocInfo(parent);
    }
  }
  return info;
}
 
Example 9
Source File: Closure_10_NodeUtil_s.java    From coming with MIT License 5 votes vote down vote up
/** Find the best JSDoc for the given node. */
static JSDocInfo getBestJSDocInfo(Node n) {
  JSDocInfo info = n.getJSDocInfo();
  if (info == null) {
    Node parent = n.getParent();
    if (parent == null) {
      return null;
    }

    if (parent.isName()) {
      return getBestJSDocInfo(parent);
    } else if (parent.isAssign()) {
      return parent.getJSDocInfo();
    } else if (isObjectLitKey(parent, parent.getParent())) {
      return parent.getJSDocInfo();
    } else if (parent.isFunction()) {
      return parent.getJSDocInfo();
    } else if (parent.isVar() && parent.hasOneChild()) {
      return parent.getJSDocInfo();
    } else if ((parent.isHook() && parent.getFirstChild() != n) ||
               parent.isOr() ||
               parent.isAnd() ||
               (parent.isComma() && parent.getFirstChild() != n)) {
      return getBestJSDocInfo(parent);
    }
  }
  return info;
}
 
Example 10
Source File: Normalize.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Mark names and properties that are constants by convention.
 */
private void annotateConstantsByConvention(Node n, Node parent) {
  Preconditions.checkState(
      n.isName()
      || n.isString()
      || n.isStringKey()
      || n.isGetterDef()
      || n.isSetterDef());

  // There are only two cases where a string token
  // may be a variable reference: The right side of a GETPROP
  // or an OBJECTLIT key.
  boolean isObjLitKey = NodeUtil.isObjectLitKey(n, parent);
  boolean isProperty = isObjLitKey ||
      (parent.isGetProp() &&
       parent.getLastChild() == n);
  if (n.isName() || isProperty) {
    boolean isMarkedConstant = n.getBooleanProp(Node.IS_CONSTANT_NAME);
    if (!isMarkedConstant &&
        NodeUtil.isConstantByConvention(
            compiler.getCodingConvention(), n, parent)) {
      if (assertOnChange) {
        String name = n.getString();
        throw new IllegalStateException(
            "Unexpected const change.\n" +
            "  name: "+ name + "\n" +
            "  parent:" + n.getParent().toStringTree());
      }
      n.putBooleanProp(Node.IS_CONSTANT_NAME, true);
    }
  }
}
 
Example 11
Source File: PeepholeRemoveDeadCode.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try removing identity assignments
 * @return the replacement node, if changed, or the original if not
 */
private Node tryFoldAssignment(Node subtree) {
  Preconditions.checkState(subtree.isAssign());
  Node left = subtree.getFirstChild();
  Node right = subtree.getLastChild();
  // Only names
  if (left.isName()
      && right.isName()
      && left.getString().equals(right.getString())) {
    subtree.getParent().replaceChild(subtree, right.detachFromParent());
    reportCodeChange();
    return right;
  }
  return subtree;
}
 
Example 12
Source File: Cardumen_00203_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * If this is an assign to a variable or its property, return it.
 * Otherwise, return null.
 */
static Assign maybeCreateAssign(Node assignNode) {
  Preconditions.checkState(NodeUtil.isAssignmentOp(assignNode));

  // Skip one level of GETPROPs or GETELEMs.
  //
  // Don't skip more than one level, because then we get into
  // situations where assigns to properties of properties will always
  // trigger side-effects, and the variable they're on cannot be removed.
  boolean isPropAssign = false;
  Node current = assignNode.getFirstChild();
  if (NodeUtil.isGet(current)) {
    current = current.getFirstChild();
    isPropAssign = true;

    if (current.isGetProp() &&
        current.getLastChild().getString().equals("prototype")) {
      // Prototype properties sets should be considered like normal
      // property sets.
      current = current.getFirstChild();
    }
  }

  if (current.isName()) {
    return new Assign(assignNode, current, isPropAssign);
  }
  return null;
}
 
Example 13
Source File: NodeModulePass.java    From js-dossier with Apache License 2.0 4 votes vote down vote up
private void visitRequireCall(NodeTraversal t, Node require, Node parent) {
  Path currentFile = inputFs.getPath(t.getSourceName());

  String modulePath = require.getSecondChild().getString();

  if (modulePath.isEmpty()) {
    t.report(require, REQUIRE_INVALID_MODULE_ID);
    return;
  }

  String moduleId = null;

  if (modulePath.startsWith(".") || modulePath.startsWith("/")) {
    Path moduleFile = currentFile.getParent().resolve(modulePath).normalize();
    if (modulePath.endsWith("/")
        || (isDirectory(moduleFile)
            && !modulePath.endsWith(".js")
            && !Files.exists(moduleFile.resolveSibling(moduleFile.getFileName() + ".js")))) {
      moduleFile = moduleFile.resolve("index.js");
    }
    moduleId = NODE.newId(moduleFile).getOriginalName();

  } else if (nodeLibrary.canRequireId(modulePath)) {
    moduleId = nodeLibrary.normalizeRequireId(modulePath);
  }

  if (moduleId != null) {
    // Only register the require statement on this module if it occurs at the global
    // scope. Assume other require statements are not declared at the global scope to
    // avoid create a circular dependency. While node can handle these, by returning
    // a partial definition of the required module, the cycle would be an error for
    // the compiler. For more information on how Node handles cycles, see:
    //     http://www.nodejs.org/api/modules.html#modules_cycles
    if (t.getScope().isGlobal()) {
      Node googRequire = call(getprop(name("goog"), string("require")), string(moduleId));

      // ClosureCheckModule enforces that goog.require statements are at the top level. To
      // compensate, if we have a require statement that is not at the top level, we introduce
      // a hidden variable at the top level that does the actual require. The compiler should
      // always inline the require making this effectively a no-op.
      //
      // Example:
      //    var Foo = require('./foo').Foo;
      //
      // Becomes:
      //    var _some_hidden_name = require('./foo');
      //    var Foo = _some_hidden_name.Foo;
      if (!parent.isName()) {
        String hiddenName = Types.toInternalVar(moduleId);

        JSDocInfoBuilder infoBuilder = new JSDocInfoBuilder(false);
        infoBuilder.recordConstancy();

        googRequireExpr.put(
            hiddenName, var(name(hiddenName).setJSDocInfo(infoBuilder.build()), googRequire));
        googRequire = name(hiddenName);
      }

      parent.replaceChild(require, googRequire.srcrefTree(require));
      t.getInput().addRequire(DependencyInfo.Require.googRequireSymbol(moduleId));

    } else {
      // For goog.module('foo'), ClosureRewriteModule produces module$exports$foo = {};, so
      // we use the transformed name in the direct reference.
      parent.replaceChild(require, name("module$exports$" + moduleId).srcrefTree(require));
    }

    t.reportCodeChange();
  }

  // Else we have an unrecognized module ID. Do nothing, leaving it to the
  // type-checking gods.
}
 
Example 14
Source File: Cardumen_00149_t.java    From coming with MIT License 4 votes vote down vote up
@Override
public boolean apply(Node n) {
  return n.isName() && n.getString().equals(name);
}
 
Example 15
Source File: Closure_116_FunctionInjector_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Determine which, if any, of the supported types the call site is.
 */
private CallSiteType classifyCallSite(Node callNode) {
  Node parent = callNode.getParent();
  Node grandParent = parent.getParent();

  // Verify the call site:
  if (NodeUtil.isExprCall(parent)) {
    // This is a simple call?  Example: "foo();".
    return CallSiteType.SIMPLE_CALL;
  } else if (NodeUtil.isExprAssign(grandParent)
      && !NodeUtil.isVarOrSimpleAssignLhs(callNode, parent)
      && parent.getFirstChild().isName()
      && !NodeUtil.isConstantName(parent.getFirstChild())) {
    // This is a simple assignment.  Example: "x = foo();"
    return CallSiteType.SIMPLE_ASSIGNMENT;
  } else if (parent.isName()
      && !NodeUtil.isConstantName(parent)
      && grandParent.isVar()
      && grandParent.hasOneChild()) {
    // This is a var declaration.  Example: "var x = foo();"
    // TODO(johnlenz): Should we be checking for constants on the
    // left-hand-side of the assignments and handling them as EXPRESSION?
    return CallSiteType.VAR_DECL_SIMPLE_ASSIGNMENT;
  } else {
    Node expressionRoot = ExpressionDecomposer.findExpressionRoot(callNode);
    if (expressionRoot != null) {
      ExpressionDecomposer decomposer = new ExpressionDecomposer(
          compiler, safeNameIdSupplier, knownConstants);
      DecompositionType type = decomposer.canExposeExpression(
          callNode);
      if (type == DecompositionType.MOVABLE) {
        return CallSiteType.EXPRESSION;
      } else if (type == DecompositionType.DECOMPOSABLE) {
        return CallSiteType.DECOMPOSABLE_EXPRESSION;
      } else {
        Preconditions.checkState(type == DecompositionType.UNDECOMPOSABLE);
      }
    }
  }

  return CallSiteType.UNSUPPORTED;
}
 
Example 16
Source File: CrossModuleCodeMotion.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Process the references to named variables
 */
private void processReference(NodeTraversal t, NamedInfo info, String name) {
  // A name is recursively defined if:
  //   1: It is calling itself.
  //   2: One of its property calls itself.
  // Recursive definition should not block movement.

  boolean recursive = false;
  Node rootNode = t.getScope().getRootNode();
  if (rootNode.isFunction()) {

    // CASE #1:
    String scopeFuncName = rootNode.getFirstChild().getString();
    Node scopeFuncParent = rootNode.getParent();
    if (scopeFuncName.equals(name)) {
      recursive = true;
    } else if (scopeFuncParent.isName() &&
        scopeFuncParent.getString().equals(name)) {
      recursive = true;
    } else {
      // CASE #2:
      // Suppose name is Foo, we keep look up the scope stack to look for
      // a scope with "Foo.prototype.bar = function() { ..... "
      for (Scope s = t.getScope();
           s.getParent() != null; s = s.getParent()) {
        Node curRoot = s.getRootNode();
        if (curRoot.getParent().isAssign()) {
          Node owner = curRoot.getParent().getFirstChild();
          while (owner.isGetProp()) {
            owner = owner.getFirstChild();
          }
          if (owner.isName() &&
              owner.getString().equals(name)) {
            recursive = true;
            break;
          }
        }
      }
    }
  }

  if (!recursive) {
    info.addUsedModule(t.getModule());
  }
}
 
Example 17
Source File: SideEffectsAnalysis.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns true if the node is a storage node.
 *
 * Only NAMEs, GETPROPs, and GETELEMs are storage nodes.
 */
private static boolean isStorageNode(Node node) {
  return node.isName() || NodeUtil.isGet(node);
}
 
Example 18
Source File: Closure_10_NodeUtil_s.java    From coming with MIT License 2 votes vote down vote up
/**
 * @return Whether the name is a reference to a variable, function or
 *       function parameter (not a label or a empty function expression name).
 */
static boolean isReferenceName(Node n) {
  return n.isName() && !n.getString().isEmpty();
}
 
Example 19
Source File: Cardumen_0087_s.java    From coming with MIT License 2 votes vote down vote up
/**
 * @return Whether the name is a reference to a variable, function or
 *       function parameter (not a label or a empty function expression name).
 */
static boolean isReferenceName(Node n) {
  return n.isName() && !n.getString().isEmpty();
}
 
Example 20
Source File: Closure_10_NodeUtil_t.java    From coming with MIT License 2 votes vote down vote up
/**
 * @return Whether the name is a reference to a variable, function or
 *       function parameter (not a label or a empty function expression name).
 */
static boolean isReferenceName(Node n) {
  return n.isName() && !n.getString().isEmpty();
}