| Code with Finding: |
class CoalesceVariableNames {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (colorings.isEmpty() || !NodeUtil.isName(n) ||
NodeUtil.isFunction(parent)) {
// Don't rename named functions.
return;
}
Var var = t.getScope().getVar(n.getString());
GraphNode<Var, ?> vNode = colorings.peek().getGraph().getNode(var);
if (vNode == null) {
// This is not a local.
return;
}
Var coalescedVar = colorings.peek().getPartitionSuperNode(var);
if (!usePseudoNames) {
if (vNode.getValue().equals(coalescedVar)) {
// The coalesced name is itself, nothing to do.
return;
}
// Rename.
n.setString(coalescedVar.name);
compiler.reportCodeChange();
if (NodeUtil.isVar(parent)) {
removeVarDeclaration(n);
}
} else {
// This code block is slow but since usePseudoName is for debugging,
// we should not sacrifice performance for non-debugging compilation to
// make this fast.
String pseudoName = null;
Set<String> allMergedNames = Sets.newTreeSet();
for (Iterator<Var> i = t.getScope().getVars(); i.hasNext();) {
Var iVar = i.next();
// Look for all the variables that can be merged (in the graph by now)
// and it is merged with the current coalscedVar.
if (colorings.peek().getGraph().getNode(iVar) != null &&
coalescedVar.equals(colorings.peek().getPartitionSuperNode(iVar))) {
allMergedNames.add(iVar.name);
}
}
// Keep its original name.
if (allMergedNames.size() == 1) {
return;
}
pseudoName = Joiner.on("_").join(allMergedNames);
while (t.getScope().isDeclared(pseudoName, true)) {
pseudoName += "$";
}
n.setString(pseudoName);
compiler.reportCodeChange();
if (!vNode.getValue().equals(coalescedVar) && NodeUtil.isVar(parent)) {
removeVarDeclaration(n);
}
}
}
}
|