dart-lang / dart-lang/language

Receiver Type Inference

Open
#3,527 9 comments 4 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

This issue is created in response to https://github.com/dart-lang/language/issues/3523.

Consider the following program.

```dart
void main() {
List xs = [1].toList();
xs.add(1.5); // Throws.
}
```

Currently the type inference mechanism in Dart always infers receivers of all kinds of invocations in the empty type context. So, the type literal `[1]` is inferred in the empty context, ultimately determining the type argument of the list literal from the types of the elements rather than from the type of the variable `xs` being initialized.

The current feature proposal suggests using type contexts of structural kind called _context type terms_ that are suitable for encoding of the downwards type information for the receivers. In the example above, the structural context for `[1]` as the receiver of the `toList` method invocation can be described as `{toList(): (...) → List}`. That structure indicates that `[1]` is supposed to have a member called `toList` that can be invoked and returns a value of type `List` upon the invocation. The type information encoded this way can help with inferring the missing type arguments from the types hinted by the surrounding type context. To enable passing the new kind of type information between the inference phases, the current proposal suggests considering context type terms first-class type schemas in the type inferring mechanism.

As a related concern, the current feature proposal suggests replacing the currently used eager approach for deciding on the inferred type with a delayed approach, where the type information is gathered from all available sources, and the most appropriate solution to the constraint system is picked among the collected ones. The delayed approach allows combining the collected type information too, for example, when some of it comes in the form of context type terms during the downwards inference phase, and some other type information comes in the form of nominal types during the upwards inference phase.

Contributor guide

Open the contributing guide

Research direction

Start by reading the linked Dart language issue 3523 and the Receiver Type Inference proposal in this issue, using the `[1].toList()` example as the motivating case. The payload names no implementation files or tests; done would require an agreed implementation of context type terms and the delayed inference approach, with the example inferring a compatible List.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.