vi-eclipse / Eclipse-JDT

Umbrella repository for managing a backlog of Eclipse-JDT-related features/issues
0 stars 0 forks source link

Quickfix Converting to Enhanced For Loop Creates Invalid Code #14

Closed HeikoKlare closed 10 months ago

HeikoKlare commented 1 year ago

Issue: https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/1008

Current Behavior

JDT provides a quickfix for converting classic for loops into enhanced for loops. When using a classic for loop to iterate through the elements of an iterator calling next() within the loop body but not using its result (such as when only counting the elements), applying the quickfix for converting into an enhanced for loop leads to syntactically incorrect code.

Example

Original code:

List<Object> list = new ArrayList<>();
int i = 0;
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
    iterator.next();
    i++;
}

After applying the quickfix:

List<Object> list = new ArrayList<>();
int i = 0;
for (Object object : list) {
    object;
    i++;
}

object; is an invalid statement.

Reproduction Environment

Happens with Eclipse 2023-09 and JDK 17.

Expected Behavior

The quick fix should always produce syntactically (and semantically) correct code. For the given example, the quick fix should either not be provided or the result should look as follows:

List<Object> list = new ArrayList<>();
int i = 0;
for (Object object : list) {
    i++;
}

Additional Information

The invalid result only occurs when performing the next() call within the loop body. When performing it within the loop header, the refactoring result is correct, e.g.:

Original code:

List<Object> list = new ArrayList<>();
int i = 0;
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext(); iterator.next()) {
    i++;
}

After applying the quickfix:

List<Object> list = new ArrayList<>();
int i = 0;
for (Object object : list) {
    i++;
}
HeikoKlare commented 10 months ago

Fix proposed and merged: https://github.com/eclipse-jdt/eclipse.jdt.ui/pull/1009