Description
Consider the following program:
class A {}
class B implements A {}
class C<X> {
R foo<R>(R Function<Y>() callback) {
R result = callback<X>();
print('X: $X, R: $R, callback: ${callback.runtimeType}');
return result;
}
}
C<List<X>> fun<X>() => C();
List<X> bar<X>(Object? o) => o is X ? <X>[o] : <X>[];
void main() {
A a = B();
var c = C<B>();
var v1 = c.foo(fun);
// 'X: B, R: C<List<Object?>>, callback: <Y0>() => C<List<Y0>>'.
var v2 = c.foo(<X>() => bar<X>(a));
// 'X: B, R: List<Object?>, callback: <Y0>() => List<Y0>'.
print([v1].runtimeType); // `v1` static type: 'C<List<Object?>>'.
print([v2].runtimeType); // `v2` static type: 'List<Object?>'.
}
The program is accepted with no compile-time errors and runs with no run-time errors with dart
. The comments indicate the printouts during execution.
However, dart analyze
rejects the program with the following error messages (using tools from a fresh commit 6a25f12):
Analyzing n009.dart... 0.5s
error • n009.dart:20:18 • The argument type 'C<List<X>> Function<X>()'
can't be assigned to the parameter type 'C<List<Z0>> Function<Y>()'.
• argument_type_not_assignable
error • n009.dart:22:18 • The argument type 'List<X> Function<X>()' can't
be assigned to the parameter type 'List<Z0> Function<Y>()'. •
argument_type_not_assignable
2 issues found.
Apparently, the behavior of the common front end is sound and useful. In particular, the inferred return type of a function literal is allowed to be a proper subtype of the chosen value for the 'imposed return type schema' which is taken from the context type, and the CFE does avoid (as it should) to leak the type variable X
into the inferred value of R
.
On the other hand, the analyzer seems to leak an auxiliary type variable Z0
into the value of R
(Z0
is not in scope, it was presumably created during inference).
Perhaps even more surprisingly, the spurious type variable Z0
also arises when the actual argument is a function fun
declared elsewhere (which means that its return type is declared explicitly, not inferred).
So what's the correct behavior here, can we just say "everything is fine with the approach taken by the CFE"?