ForStmt.prettyPrint reimplements VarDeclStmt.prettyPrint with errors

Issue #149 resolved
Loïc Girault created an issue

Parsing this sample of code :

package p;

import java.util.Enumeration;
import java.util.Vector;

class A {
    void m(Vector<Object> v){
        for(Enumeration<?> e = v.elements(); e.hasMoreElements();){
            Object o = e.nextElement();
        }
    }
}

and then pretty printing it gives :

package p;
import java.util.Enumeration;
import java.util.Vector;

class A {
  void m(Vector<Object> v) {
    for (java.util.Enumeration<wildcards.? extends java.lang.Object> e = v.elements(); e.hasMoreElements(); ) {
      Object o = e.nextElement();
    }
  }
}

The problem is in java4/frontend/PrettyPrintUtil.jrag. Instead of reusing VarDeclStmt.prettyprint the ForStmt.prettyPrint reimplements it with some kind of special case for arrays.

To solve it, I've replaced

public void ForStmt.prettyPrint(PrettyPrinter out) {
    out.print("for (");
    if (getNumInitStmt() > 0) {
      if (getInitStmt(0) instanceof VarDeclStmt) {
        /* 36 lines of code (clone ?) */
      } else if (getInitStmt(0) instanceof ExprStmt) {
       /* code */
      } else {
        throw new Error("Unexpected initializer in for loop: " + getInitStmt(0));
      }
    }
    out.print("; ");

    /*end of the method*/
}

by the following

public void ForStmt.prettyPrint(PrettyPrinter out) {
    out.print("for (");
    if (getNumInitStmt() > 0) {
      if (getInitStmt(0) instanceof VarDeclStmt) {
           out.print((VarDeclStmt)getInitStmt(0));
      } else if (getInitStmt(0) instanceof ExprStmt) {
       /* code */
       out.print("; ");
      } else {
        throw new Error("Unexpected initializer in for loop: " + getInitStmt(0));
      }
    }

    /*end of the method*/
}

Comments (4)

  1. Loïc Girault reporter

    In the end my fix has a problem. I've encoutered a for stmt without init stmt. The result is a missing semicolon Solution: add an else branch in the pretty printing

    public void ForStmt.prettyPrint(PrettyPrinter out) {
        out.print("for (");
        if (getNumInitStmt() > 0) {
         /* ... */
        }
        else
           out.print("; ");
    
        /* ... */
    }
    
  2. Log in to comment