Paul King created GROOVY-12775:
----------------------------------

             Summary: STC: the result of collect is not checked against a 
target's Class<? extends X> type argument
                 Key: GROOVY-12775
                 URL: https://issues.apache.org/jira/browse/GROOVY-12775
             Project: Groovy
          Issue Type: Bug
          Components: Static Type Checker
    Affects Versions: 6.0.0, 5.1.3, 4.0.33
            Reporter: Paul King


{code:groovy}
@groovy.transform.CompileStatic
class C {
    static class IntList extends ArrayList<Integer> { }

    static <T> List<Class<? extends T>> classes(List<Object> items) {
        List<Class<? extends T>> list = items.collect { it.getClass() }
        list
    }
    static List<String> strings(Class<? extends List<String>> type) {
        List<String> list = type.getConstructor().newInstance()
        list.add('x')
        list
    }
    static String hex(Integer i) { Integer.toHexString(i) }

    static main(args) {
        List<Class<? extends List<String>>> lists = [IntList].collect { it }
        IntList ints = (IntList) strings(lists[0])
        println ints.get(0).intValue()             // (1)

        List<Class<? extends Integer>> numbers = classes(['a'])
        println hex(numbers[0].getConstructor(String).newInstance('1'))   // (2)
    }
}
{code}

Both {{collect}} calls compile with 4.0.33, 5.1.3 and 6.0.0:
* (1) {{[IntList].collect \{ it \}}} is accepted as a {{List<Class<? extends 
List<String>>>}}. A {{String}} is then added to an {{IntList}}: 
{{ClassCastException}} under {{@CompileStatic}}, {{MissingMethodException}} 
under {{@TypeChecked}}.
* (2) {{items.collect \{ it.getClass() \}}} for a {{List<Object>}} is accepted 
as a {{List<Class<? extends T>>}}. A {{Class<String>}} is returned as a 
{{Class<? extends Integer>}}: under {{@TypeChecked}}, {{hex}} fails with 
{{MissingMethodException ... (String)}}; under {{@CompileStatic}} it prints 
{{31}}, the {{String}} {{"1"}} converted to the character code 49.

javac rejects the {{Stream.map(...).collect(...)}} equivalents of both: 
"inference variable T has incompatible bounds".

Master rejects both since GROOVY-12714; a build of its parent commit accepts 
both. With PR #3293, both compile again, while the spread forms 
({{rawLists*.getClass()}}, {{items*.getClass()}}) and {{collect}} over a 
{{Class<? extends List>}} parameter are rejected.

*Expected:* the {{collect}} forms are checked against the target like the 
spread forms. {{@NotYetImplemented}} tests, 
{{GenericsSTCTest#testClassArgumentOfCollectIsCheckedAgainstTarget}} and 
{{#testCollectOfClassIsCheckedAgainstEnclosingTypeParameter}}, record these in 
PR #3293.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to