openrewrite / rewrite-static-analysis

OpenRewrite recipes for identifying and fixing static analysis issues.
Apache License 2.0
27 stars 43 forks source link

Recipe InlineVariable and Enum array results in non compilable code #9

Open jbessels opened 1 year ago

jbessels commented 1 year ago

I have the following public enum ImportType. With the following method

  public static ImportType[] getList() {
        ImportType[] list = {ImportType.TIMETABLE, ImportType.DUTIES};
        return list;
    }

org.openrewrite.java.cleanup.InlineVariable translates this to

public static ImportType[] getList() {
        return {ImportType.TIMETABLE, ImportType.DUTIES};
    }

This does no longer compile. Correct code suggested by IntelliJ

 public static ImportType[] getList() {
        return new ImportType[]{ImportType.TIMETABLE, ImportType.DUTIES};
    }

I hope this is enough to reproduce the issue.

knutwannheden commented 1 year ago

When refactoring the following Java class using the InlineVariable recipe, the result looks correct (it inlines the newMapSortedByOrder variable), but as stated in the issue, it doesn't compile anymore:

  import java.util.Comparator;
  import java.util.LinkedHashMap;
  import java.util.Map;
  import java.util.stream.Collectors;

  class Test {
      void test() {
          new MapDropdownChoice<String, Integer>(() -> {
              Map<String, Integer> statuses = new java.util.HashMap<>();
              Map<String, Integer> newMapSortedByOrder = statuses.entrySet().stream()
                      .sorted(Comparator.comparingInt(e -> e.getValue()))
                      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
              return newMapSortedByOrder;
          });
      }
      static class MapDropdownChoice<K, V> extends DropdownChoice<K> {
          public MapDropdownChoice(final IModel<? extends Map<K, ? extends V>> choiceMap) {
          }
      }

      interface IModel<T> {
          T getObject();
      }
      static class DropdownChoice<T> {
      }
  }

Note The problem can probably be boiled down even more.