Skip to content

Function argument rejected based on faulty inferred parameter type #55644

Open
@eernstg

Description

@eernstg

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"?

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-dart-modelFor issues related to conformance to the language spec in the parser, compilers or the CLI analyzer.dart-model-analyzer-specIssues with the analyzer's implementation of the language spectype-bugIncorrect behavior (everything from a crash to more subtle misbehavior)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions