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

STC does not properly handle try/catch in flow typing leading to type unsafety

    XMLWordPrintableJSON

Details

    Description

      I have the following incorrect program

      class Main {
        public static void main(String[] args) {
          var p1 = (java.lang.Appendable) null;
          if (false)  {
          } else {
            p1 = 51
          };
          //if (false) {} else {p1 = (java.lang.Appendable) null;}
          try {} catch(Exception e) { p1 = (java.lang.Appendable) null; }
          final java.lang.Appendable p2 = p1
        }
      }

      Actual behavior

      The compiler accepts the program, but I get a ClassCastException

      Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '51' with class 'java.lang.Integer' to class 'java.lang.Appendable'
              at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnSAM(DefaultTypeTransformation.java:416)
              at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnNumber(DefaultTypeTransformation.java:329)
              at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:248)
              at org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache(IndyInterface.java:336)
              at Main.main(test.groovy:11)
       

      Expected behavior

      The code should have been rejected with

      org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
      test.groovy: 11: [Static type checking] - Cannot assign value of type java.lang.Object to variable of type java.lang.Appendable
       @ line 11, column 37.
             final java.lang.Appendable p2 = p1
                                             ^1 error 

      Notes

      When replacing try/catch with another if/else like so:

      class Main {
        public static void main(String[] args) {
          var p1 = (java.lang.Appendable) null;
          if (false)  {
          } else {
            p1 = 51
          };
          if (false) {} else {p1 = (java.lang.Appendable) null;}
          //try {} catch(Exception e) { p1 = (java.lang.Appendable) null; }
          final java.lang.Appendable p2 = p1
        }
      } 

      the compiler rejected the code as expected.

      Attachments

        Activity

          People

            emilles Eric Milles
            theosot Thodoris Sotiropoulos
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: