Declawer: foreach over array

View: New views
1 Messages — Rating Filter:   Alert me  

Declawer: foreach over array

by jcsahnwaldt :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

I needed Declawer to handle foreach loops over arrays,
so I added a little code that does this.

I also fixed a bug - when declawer generates the code for the
foreach loop, it always used the same name for the iterator,
which led to name clashes with nested foreach loops. I fixed
that by simply incrementing a counter, so a new name is used
for each temporary variable. There may be better solutions.

I changed the part that generates the foreach loop for
collections to use the idiom suggested in Josh Bloch's
"Effective Java": for (Iterator i = c.iterator(); i.hasNext(); ) {...}
It doesn't change the variable scopes, it's just a little
more compact than using an extra block.

Here's the new code in com.sun.tools.javac.tree.Pretty.
It replaces the old version of visitForeachLoop().


private static final AtomicInteger tempVarCount = new AtomicInteger();

private String declawerVar( String name )
{
  return "declawer$"+tempVarCount.getAndIncrement()+"$"+name;
}

public void visitForeachLoop(ForeachLoop tree)
{
  // replace for each loops with Iteration counterparts
  if (tree.expr.type.tag == TypeTags.ARRAY)
  {
    String arrayVar = declawerVar("array");
    String lengthVar = declawerVar("length");
    String countVar = declawerVar("count");
    print("{");
    print(tree.expr.type+" "+arrayVar+" = ");
    printExpr(tree.expr);
    print(";");
    print("int "+lengthVar+" = "+arrayVar+".length;");
    print("for (int "+countVar+" = 0; "+countVar+" < "+lengthVar+"; "+countVar+"++) {");
    printExpr(tree.var);
    print("; ");
    print(tree.var.name+" = "+arrayVar+"["+countVar+"];");
    printStat(tree.body);
    print("}}");
  }
  else
  {
    String iterVar = declawerVar("iter");
    print("for (java.util.Iterator "+iterVar+" = ");
    printExpr(tree.expr);
    print(".iterator(); "+iterVar+".hasNext(); )");
    print("{");
    printExpr(tree.var);
    print("; ");
    print(tree.var.name+" = ("+tree.var.type+") "+iterVar+".next();");
    printStat(tree.body);
    print("}");
  }
}

I attached the new version of Pretty.java, and a new version
of the test class Testy.java.

Declawer is really neat! We need to run some of our Java 1.5
code inside a Oracle 10g server, which only has a 1.4 JVM.
With Declawer, we can do that without removing all the generics
from our code.

Is Declawer in any public SVN or CVS repository?

Bye,
Christopher.




---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@...
For additional commands, e-mail: dev-help@...

Testy.java (1K) Download Attachment
Pretty.java (33K) Download Attachment