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

The following examples show how to use com.google.javascript.rhino.Node#setString() . 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_79_Normalize_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Rewrite the function declaration from:
 *   function x() {}
 *   FUNCTION
 *     NAME
 *     LP
 *     BLOCK
 * to:
 *   var x = function() {};
 *   VAR
 *     NAME
 *       FUNCTION
 *         NAME (w/ empty string)
 *         LP
 *         BLOCK
 */
private void rewriteFunctionDeclaration(Node n) {
  // Prepare a spot for the function.
  Node oldNameNode = n.getFirstChild();
  Node fnNameNode = oldNameNode.cloneNode();
  Node var = new Node(Token.VAR, fnNameNode, n.getLineno(), n.getCharno());
  var.copyInformationFrom(n);

  // Prepare the function
  oldNameNode.setString("");

  // Move the function
  Node parent = n.getParent();
  parent.replaceChild(n, var);
  fnNameNode.addChildToFront(n);

  reportCodeChange("Function declaration");
}
 
Example 2
Source File: Closure_72_RenameLabels_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Rename label references in breaks and continues.
 * @param node The break or continue node.
 */
private void visitBreakOrContinue(Node node) {
  Node nameNode = node.getFirstChild();
  if (nameNode != null) {
    // This is a named break or continue;
    String name = nameNode.getString();
    Preconditions.checkState(name.length() != 0);
    LabelInfo li = getLabelInfo(name);
    if (li != null) {
      String newName = getNameForId(li.id);
      // Mark the label as referenced so it isn't removed.
      li.referenced = true;
      if (!name.equals(newName)) {
        // Give it the short name.
        nameNode.setString(newName);
        compiler.reportCodeChange();
      }
    }
  }
}
 
Example 3
Source File: Closure_26_ProcessCommonJSModules_t.java    From coming with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.isName()) {
    String name = n.getString();
    if (suffix.equals(name)) {
      return;
    }
    if (EXPORTS.equals(name)) {
      n.setString(suffix);
      n.putProp(Node.ORIGINALNAME_PROP, EXPORTS);
    } else {
      Scope.Var var = t.getScope().getVar(name);
      if (var != null && var.isGlobal()) {
        n.setString(name + "$$" + suffix);
        n.putProp(Node.ORIGINALNAME_PROP, name);
      }
    }
  }
}
 
Example 4
Source File: Closure_72_RenameLabels_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Rename label references in breaks and continues.
 * @param node The break or continue node.
 */
private void visitBreakOrContinue(Node node) {
  Node nameNode = node.getFirstChild();
  if (nameNode != null) {
    // This is a named break or continue;
    String name = nameNode.getString();
    Preconditions.checkState(name.length() != 0);
    LabelInfo li = getLabelInfo(name);
    if (li != null) {
      String newName = getNameForId(li.id);
      // Mark the label as referenced so it isn't removed.
      li.referenced = true;
      if (!name.equals(newName)) {
        // Give it the short name.
        nameNode.setString(newName);
        compiler.reportCodeChange();
      }
    }
  }
}
 
Example 5
Source File: Closure_9_ProcessCommonJSModules_s.java    From coming with MIT License 6 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.isName()) {
    String name = n.getString();
    if (suffix.equals(name)) {
      return;
    }
    if (EXPORTS.equals(name)) {
      n.setString(suffix);
      n.putProp(Node.ORIGINALNAME_PROP, EXPORTS);
    } else {
      Scope.Var var = t.getScope().getVar(name);
      if (var != null && var.isGlobal()) {
        n.setString(name + "$$" + suffix);
        n.putProp(Node.ORIGINALNAME_PROP, name);
      }
    }
  }
}
 
Example 6
Source File: Closure_49_MakeDeclaredNamesUnique_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * For the Var declared in the current scope determine if it is possible
 * to revert the name to its orginal form without conflicting with other
 * values.
 */
void handleScopeVar(Var v) {
  String name  = v.getName();
  if (containsSeparator(name) && !getOrginalName(name).isEmpty()) {
    String newName = findReplacementName(name);
    referencedNames.remove(name);
    // Adding a reference to the new name to prevent either the parent
    // scopes or the current scope renaming another var to this new name.
    referencedNames.add(newName);
    List<Node> references = nameMap.get(name);
    Preconditions.checkState(references != null);
    for (Node n : references) {
      Preconditions.checkState(n.getType() == Token.NAME);
      n.setString(newName);
    }
    compiler.reportCodeChange();
    nameMap.remove(name);
  }
}
 
Example 7
Source File: Closure_9_ProcessCommonJSModules_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Rewrite module.exports to moduleName.module$exports.
 */
private void visitModuleExports(Node prop) {
  String moduleName = guessCJSModuleName(prop.getSourceFileName());
  Node module = prop.getChildAtIndex(0);
  module.putProp(Node.ORIGINALNAME_PROP, "module");
  module.setString(moduleName);
  Node exports = prop.getChildAtIndex(1);
  exports.putProp(Node.ORIGINALNAME_PROP, "exports");
  exports.setString("module$exports");
  modulesWithExports.add(moduleName);
}
 
Example 8
Source File: TransformAMDToCJSModule.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  if (n.isName() && from.equals(n.getString())) {
    n.setString(to);
    n.putProp(Node.ORIGINALNAME_PROP, from);
  }
}
 
Example 9
Source File: RenameLabels.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Rename or remove labels.
 * @param node  The label node.
 * @param parent The parent of the label node.
 */
private void visitLabel(Node node, Node parent) {
  Node nameNode = node.getFirstChild();
  Preconditions.checkState(nameNode != null);
  String name = nameNode.getString();
  LabelInfo li = getLabelInfo(name);
  // This is a label...
  if (li.referenced || !removeUnused) {
    String newName = getNameForId(li.id);
    if (!name.equals(newName)) {
      // ... and it is used, give it the short name.
      nameNode.setString(newName);
      compiler.reportCodeChange();
    }
  } else {
    // ... and it is not referenced, just remove it.
    Node newChild = node.getLastChild();
    node.removeChild(newChild);
    parent.replaceChild(node, newChild);
    if (newChild.isBlock()) {
      NodeUtil.tryMergeBlock(newChild);
    }
    compiler.reportCodeChange();
  }

  // Remove the label from the current stack of labels.
  namespaceStack.peek().renameMap.remove(name);
}
 
Example 10
Source File: AliasExternals.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Replace uses of a global with its aliased name.
 */
private void replaceGlobalUse(Node globalUse) {
  String globalName = globalUse.getString();
  if (globals.get(globalName).aliasAccessor) {
    globalUse.setString("GLOBAL_" + globalName);

    // None of the aliases are marked as @const.
    // Because we're reusing the original ref node,
    // we need to update it to reflect this.
    globalUse.putBooleanProp(Node.IS_CONSTANT_NAME, false);

    compiler.reportCodeChange();
  }
}
 
Example 11
Source File: Closure_72_RenameLabels_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Rename or remove labels.
 * @param node  The label node.
 * @param parent The parent of the label node.
 */
private void visitLabel(Node node, Node parent) {
  Node nameNode = node.getFirstChild();
  Preconditions.checkState(nameNode != null);
  String name = nameNode.getString();
  LabelInfo li = getLabelInfo(name);
  // This is a label...
  if (li.referenced) {
    String newName = getNameForId(li.id);
    if (!name.equals(newName)) {
      // ... and it is used, give it the short name.
      nameNode.setString(newName);
      compiler.reportCodeChange();
    }
  } else {
    // ... and it is not referenced, just remove it.
    Node newChild = node.getLastChild();
    node.removeChild(newChild);
    parent.replaceChild(node, newChild);
    if (newChild.getType() == Token.BLOCK) {
      NodeUtil.tryMergeBlock(newChild);
    }
    compiler.reportCodeChange();
  }

  // Remove the label from the current stack of labels.
  namespaceStack.peek().renameMap.remove(name);
}
 
Example 12
Source File: Closure_72_RenameLabels_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Rename or remove labels.
 * @param node  The label node.
 * @param parent The parent of the label node.
 */
private void visitLabel(Node node, Node parent) {
  Node nameNode = node.getFirstChild();
  Preconditions.checkState(nameNode != null);
  String name = nameNode.getString();
  LabelInfo li = getLabelInfo(name);
  // This is a label...
  if (li.referenced || !removeUnused) {
    String newName = getNameForId(li.id);
    if (!name.equals(newName)) {
      // ... and it is used, give it the short name.
      nameNode.setString(newName);
      compiler.reportCodeChange();
    }
  } else {
    // ... and it is not referenced, just remove it.
    Node newChild = node.getLastChild();
    node.removeChild(newChild);
    parent.replaceChild(node, newChild);
    if (newChild.getType() == Token.BLOCK) {
      NodeUtil.tryMergeBlock(newChild);
    }
    compiler.reportCodeChange();
  }

  // Remove the label from the current stack of labels.
  namespaceStack.peek().renameMap.remove(name);
}
 
Example 13
Source File: Closure_103_DisambiguateProperties_t.java    From coming with MIT License 5 votes vote down vote up
/** Renames all properties with references on more than one type. */
void renameProperties() {
  int propsRenamed = 0, propsSkipped = 0, instancesRenamed = 0,
      instancesSkipped = 0, singleTypeProps = 0;

  for (Property prop : properties.values()) {
    if (prop.shouldRename()) {
      Map<T, String> propNames = buildPropNames(prop.getTypes(), prop.name);

      ++propsRenamed;
      prop.expandTypesToSkip();
      UnionFind<T> types = prop.getTypes();
      for (Node node : prop.renameNodes) {
        T rootType = prop.rootTypes.get(node);
        if (prop.shouldRename(rootType)) {
          String newName = propNames.get(rootType);
          node.setString(newName);
          compiler.reportCodeChange();
          ++instancesRenamed;
        } else {
          ++instancesSkipped;
        }
      }
    } else {
      if (prop.skipRenaming) {
        ++propsSkipped;
      } else {
        ++singleTypeProps;
      }
    }
  }
  logger.info("Renamed " + instancesRenamed + " instances of "
              + propsRenamed + " properties.");
  logger.info("Skipped renaming " + instancesSkipped + " invalidated "
              + "properties, " + propsSkipped + " instances of properties "
              + "that were skipped for specific types and " + singleTypeProps
              + " properties that were referenced from only one type.");
}
 
Example 14
Source File: DisambiguateProperties.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Renames all properties with references on more than one type. */
void renameProperties() {
  int propsRenamed = 0, propsSkipped = 0, instancesRenamed = 0,
      instancesSkipped = 0, singleTypeProps = 0;

  for (Property prop : properties.values()) {
    if (prop.shouldRename()) {
      Map<T, String> propNames = buildPropNames(prop.getTypes(), prop.name);

      ++propsRenamed;
      prop.expandTypesToSkip();
      UnionFind<T> types = prop.getTypes();
      for (Node node : prop.renameNodes) {
        T rootType = prop.rootTypes.get(node);
        if (prop.shouldRename(rootType)) {
          String newName = propNames.get(rootType);
          node.setString(newName);
          compiler.reportCodeChange();
          ++instancesRenamed;
        } else {
          ++instancesSkipped;
        }
      }
    } else {
      if (prop.skipRenaming) {
        ++propsSkipped;
      } else {
        ++singleTypeProps;
      }
    }
  }
  logger.fine("Renamed " + instancesRenamed + " instances of "
              + propsRenamed + " properties.");
  logger.fine("Skipped renaming " + instancesSkipped + " invalidated "
              + "properties, " + propsSkipped + " instances of properties "
              + "that were skipped for specific types and " + singleTypeProps
              + " properties that were referenced from only one type.");
}
 
Example 15
Source File: NameAnonymousFunctions.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void setFunctionName(String name, Node fnNode) {
  Node fnNameNode = fnNode.getFirstChild();
  String uniqueName = getLikelyNonConflictingName(name);
  fnNameNode.setString(uniqueName);
  compiler.reportCodeChange();
  namedCount++;
  bytesUsed += uniqueName.length();
}
 
Example 16
Source File: Closure_26_ProcessCommonJSModules_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Rewrite module.exports to moduleName.module$exports.
 */
private void visitModuleExports(Node prop) {
  String moduleName = guessCJSModuleName(prop.getSourceFileName());
  Node module = prop.getChildAtIndex(0);
  module.putProp(Node.ORIGINALNAME_PROP, "module");
  module.setString(moduleName);
  Node exports = prop.getChildAtIndex(1);
  exports.putProp(Node.ORIGINALNAME_PROP, "exports");
  exports.setString("module$exports");
  modulesWithExports.add(moduleName);
}
 
Example 17
Source File: Closure_49_MakeDeclaredNamesUnique_t.java    From coming with MIT License 5 votes vote down vote up
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
  switch (n.getType()) {
    case Token.NAME:
      String newName = getReplacementName(n.getString());
      if (newName != null) {
        Renamer renamer = nameStack.peek();
        if (renamer.stripConstIfReplaced()) {
          // TODO(johnlenz): Do we need to do anything about the javadoc?
          n.removeProp(Node.IS_CONSTANT_NAME);
        }
        n.setString(newName);
        t.getCompiler().reportCodeChange();
      }
      break;

    case Token.FUNCTION:
      // Remove the function body scope
      nameStack.pop();
      // Remove function recursive name (if any).
      nameStack.pop();
      break;

    case Token.LP:
      // Note: The parameters and function body variables live in the
      // same scope, we introduce the scope when in the "shouldTraverse"
      // visit of LP, but remove it when when we exit the function above.
      break;

    case Token.CATCH:
      // Remove catch except name from the stack of names.
      nameStack.pop();
      break;
  }
}
 
Example 18
Source File: ReplaceStrings.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Replaces a string expression with a short encoded string expression.
 *
 * @param t The traversal
 * @param expr The expression node
 * @param parent The expression node's parent
 * @return The replacement node (or the original expression if no replacement
 *         is made)
 */
private Node replaceExpression(NodeTraversal t, Node expr, Node parent) {
  Node replacement;
  String key = null;
  String replacementString;
  switch (expr.getType()) {
    case Token.STRING:
      key = expr.getString();
      replacementString = getReplacement(key);
      replacement = IR.string(replacementString);
      break;
    case Token.ADD:
      StringBuilder keyBuilder = new StringBuilder();
      Node keyNode = IR.string("");
      replacement = buildReplacement(expr, keyNode, keyBuilder);
      key = keyBuilder.toString();
      replacementString = getReplacement(key);
      keyNode.setString(replacementString);
      break;
    case Token.NAME:
      // If the referenced variable is a constant, use its value.
      Scope.Var var = t.getScope().getVar(expr.getString());
      if (var != null && var.isConst()) {
        Node value = var.getInitialValue();
        if (value != null && value.isString()) {
          key = value.getString();
          replacementString = getReplacement(key);
          replacement = IR.string(replacementString);
          break;
        }
      }
      return expr;
    default:
      // This may be a function call or a variable reference. We don't
      // replace these.
      return expr;
  }

  Preconditions.checkNotNull(key);
  Preconditions.checkNotNull(replacementString);
  recordReplacement(expr, key, replacementString);

  parent.replaceChild(expr, replacement);
  compiler.reportCodeChange();
  return replacement;
}
 
Example 19
Source File: Closure_118_DisambiguateProperties_t.java    From coming with MIT License 4 votes vote down vote up
/** Renames all properties with references on more than one type. */
void renameProperties() {
  int propsRenamed = 0, propsSkipped = 0, instancesRenamed = 0,
      instancesSkipped = 0, singleTypeProps = 0;

  Set<String> reported = Sets.newHashSet();
  for (Property prop : properties.values()) {
    if (prop.shouldRename()) {
      Map<T, String> propNames = buildPropNames(prop.getTypes(), prop.name);

      ++propsRenamed;
      prop.expandTypesToSkip();
      for (Node node : prop.renameNodes) {
        T rootType = prop.rootTypes.get(node);
        if (prop.shouldRename(rootType)) {
          String newName = propNames.get(rootType);
          node.setString(newName);
          compiler.reportCodeChange();
          ++instancesRenamed;
        } else {
          ++instancesSkipped;

          CheckLevel checkLevelForProp = propertiesToErrorFor.get(prop.name);
          if (checkLevelForProp != null &&
              checkLevelForProp != CheckLevel.OFF &&
              !reported.contains(prop.name)) {
            reported.add(prop.name);
            compiler.report(JSError.make(
                NodeUtil.getSourceName(node), node,
                checkLevelForProp,
                Warnings.INVALIDATION_ON_TYPE, prop.name,
                rootType.toString(), ""));
          }
        }
      }
    } else {
      if (prop.skipRenaming) {
        ++propsSkipped;
      } else {
        ++singleTypeProps;
      }
    }
  }
  logger.fine("Renamed " + instancesRenamed + " instances of "
              + propsRenamed + " properties.");
  logger.fine("Skipped renaming " + instancesSkipped + " invalidated "
              + "properties, " + propsSkipped + " instances of properties "
              + "that were skipped for specific types and " + singleTypeProps
              + " properties that were referenced from only one type.");
}
 
Example 20
Source File: Closure_118_DisambiguateProperties_s.java    From coming with MIT License 4 votes vote down vote up
/** Renames all properties with references on more than one type. */
void renameProperties() {
  int propsRenamed = 0, propsSkipped = 0, instancesRenamed = 0,
      instancesSkipped = 0, singleTypeProps = 0;

  Set<String> reported = Sets.newHashSet();
  for (Property prop : properties.values()) {
    if (prop.shouldRename()) {
      Map<T, String> propNames = buildPropNames(prop.getTypes(), prop.name);

      ++propsRenamed;
      prop.expandTypesToSkip();
      for (Node node : prop.renameNodes) {
        T rootType = prop.rootTypes.get(node);
        if (prop.shouldRename(rootType)) {
          String newName = propNames.get(rootType);
          node.setString(newName);
          compiler.reportCodeChange();
          ++instancesRenamed;
        } else {
          ++instancesSkipped;

          CheckLevel checkLevelForProp = propertiesToErrorFor.get(prop.name);
          if (checkLevelForProp != null &&
              checkLevelForProp != CheckLevel.OFF &&
              !reported.contains(prop.name)) {
            reported.add(prop.name);
            compiler.report(JSError.make(
                NodeUtil.getSourceName(node), node,
                checkLevelForProp,
                Warnings.INVALIDATION_ON_TYPE, prop.name,
                rootType.toString(), ""));
          }
        }
      }
    } else {
      if (prop.skipRenaming) {
        ++propsSkipped;
      } else {
        ++singleTypeProps;
      }
    }
  }
  logger.fine("Renamed " + instancesRenamed + " instances of "
              + propsRenamed + " properties.");
  logger.fine("Skipped renaming " + instancesSkipped + " invalidated "
              + "properties, " + propsSkipped + " instances of properties "
              + "that were skipped for specific types and " + singleTypeProps
              + " properties that were referenced from only one type.");
}