Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-8383

OptimizerVisitor#setConstField not @CS friendly

    Details

    • Type: Bug
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 2.4.13
    • Component/s: None
    • Labels:
      None

      Description

      @groovy.transform.CompileStatic
      def method() {
          Long wrapper = 2L
          long prim = 2L
      }
      method()
      

      gives:

      java.lang.NoSuchFieldError: $const$0
      

      swapping the second 2L with 3L or wrapper side steps the problem.
      The primitive and wrapper constants are being deemed the same but the types won't match (J vs Ljava/lang/Long;). Other types are also affected but seemingly not int or double. Swapping the order has no affect. I assume the code in OptimizerVisitor#setConstField is not @CS friendly. That code has an early return for Integer and Double.

      In addition, the current implementation has a limitation if the user uses field names similar to what the visitor generates, e.g. $const$0. A similar error will occur if such a field exists but has the wrong type:

      class Bar {
        private String $const$0 = 'bar'
        def method2() {
          Long wrapper3 = 20L
        }
      }
      new Bar().method2() // => NoSuchFieldError
      

      And if it happens to be the "correct" type it can lead to weird errors:

      class Bar {
        private static long $const$0 = 42
        def method2() {
          long prim4 = 21L
        }
      }
      assert new Bar().method2() == 42 // expected 21!
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                paulk Paul King
                Reporter:
                paulk Paul King
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: