dart-lang / dart-lang/language

Type inference might exploit some 'immediate' types

Open
#253 4 comments 0 reactions 0 assignees View on GitHub
feature type-inference
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

This issue is a proposal that we use a notion of _immediate_ types during type inference.

Looking at the behavior of type inference in the analyzer and in CFE, the following difference stands out:

```dart
class A { A(_); }
var x = () => y;
var y = new A(x);

main() => print(x());
```

This program runs with no error using `dart`, but `dartanalyzer` emits the following error:

```
error • The type of 'x' can't be inferred because it depends on itself through the cycle: [y, x] at n024.dart:5:15 • strong_mode_top_level_cycle
```

I would expect type inference as performed in the analyzer to be the closest match to the upcoming specification of type inference, but the fact that the program is accepted by the CFE could be taken as a hint that this need not be an error.

The point is that there is no way the type of the initializer of `y` could ever be affected by the typing of `x`, the initializer type would be `A`, or there is a compile-time error (because `x` does or does not have a suitable type as an actual argument of the given generative constructor for `A`).

We would be able to use a concept that we have discussed a while back: Certain expressions have an _evident_ or _immediate_ type, which basically means that we can ignore actual arguments and other subterms of a given expression, because it's either a compile-time error or it is an expression of type _T_ for some type _T_ that we can determine based on an inspection that does not need to traverse those subterms.

With that, type inference could give `y` the type `A` and make it available for type inference without running inference on `x`, and the program would be accepted is it is with the CFE.

Of course, there are many different expressions for which we could define an immediate type, and we wouldn't want to go very far down that rabbit hole. An instance creation for a non-generic class or for a generic class where type arguments have been given explicitly is a typical example, and so is an invocation of a function/method whose return type does not depend on inferred types; in both cases we could infer the type immediately (without looking at actual arguments), and then we'd handle any inference steps associated with the actual arguments later on.

This would give us an improvement in the level of support that we can provide to developers through type inference, and it's a non-breaking change (because it makes no difference other than eliminating some "cyclic inference" errors).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.