[
https://issues.apache.org/jira/browse/GROOVY-12765?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
]
Daniel Sun reassigned GROOVY-12765:
-----------------------------------
Assignee: Daniel Sun
> STC: a diamond constructor call is not checked against its target, so a
> Holder<Number> can wrap a List<Integer>
> ---------------------------------------------------------------------------------------------------------------
>
> Key: GROOVY-12765
> URL: https://issues.apache.org/jira/browse/GROOVY-12765
> Project: Groovy
> Issue Type: Bug
> Components: Static compilation, Static Type Checker
> Affects Versions: 4.0.33, 5.1.3, 6.0.0
> Reporter: Paul King
> Assignee: Daniel Sun
> Priority: Major
>
> Under {{@TypeChecked}} and {{@CompileStatic}}, a constructor call with a
> diamond takes its type arguments from the target of the assignment, but the
> arguments of the constructor are not checked against them. {{Holder<Number>
> holder = new Holder<>(integers)}} compiles for a {{List<Integer> integers}}
> and a {{Holder(List<T>)}} constructor, although a {{List<Integer>}} is not a
> {{List<Number>}}. The holder can then add a {{Double}} to the
> {{ArrayList<Integer>}}:
> {code:groovy}
> class Holder<T> {
> List<T> items
> Holder(List<T> items) { this.items = items }
> }
> @groovy.transform.CompileStatic
> def test(List<Integer> integers) {
> Holder<Number> holder = new Holder<>(integers)
> holder.items.add(1.5d)
> }
> List<Integer> integers = new ArrayList<Integer>([1])
> test(integers)
> println integers*.getClass()*.simpleName // [Integer, Double]
> println Collections.max(integers) // ClassCastException
> {code}
> Output with 4.0.33, 6.0.0 and current master:
> {noformat}
> [Integer, Double]
> java.lang.ClassCastException: class java.lang.Integer cannot be cast to class
> java.lang.Double
> {noformat}
> The same happens for a {{List<? extends Integer>}} argument.
> Written with the type argument, the call is rejected:
> {noformat}
> Holder<Number> holder = new Holder<Number>(integers)
> [Static type checking] - Cannot call
> Holder#<init>(java.util.List<java.lang.Number>) with arguments
> [java.util.List<java.lang.Integer>]
> {noformat}
> javac rejects the diamond form too: {{incompatible types: cannot infer type
> arguments for Holder<>}}.
> *Expected:* a diamond whose type arguments come from the target is checked as
> if they were written out, so the call is rejected with the same error as
> {{new Holder<Number>(integers)}}. A diamond with no target, such as {{def
> holder = new Holder<>(integers)}}, keeps inferring {{Holder<Integer>}} from
> the arguments.
> A test marked {{@NotYetImplemented}},
> {{GenericsSTCTest#testDiamondTypeArgumentsAreCheckedAgainstTarget}}, records
> this; it comes with the GROOVY-12754/12755/12756 changes (PR #3293).
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)