dart-lang / dart-lang/language

Promoting type variables

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

Description

We can promote the value of a local variable by `if (x is int)`, but we cannot similarly promote the type of a type variable.

Assume we have some types that can be specialized:
```dart
class Foo { someMethods }
class ComparableFoo implements Foo { ... }
```
and we then want to do:
```dart
Foo foo(...) {
if (T <: Comparable) return ComparableFoo(...);
return Foo(...);
}
```
We lack both the ability to compare types and the ability to promote `T` to `T & Comparable`.

Assume that we have some ability to compare types (something people often try to do using `T is Comparable`, which fails badly), so as a strawman let's introduce a `<:` operator ... which would probably be possible to add to the language. It takes a type on both sides of the operator, which means that we might need to syntactically allow writing `List <: T` as well.

Then a test like `if (T <: someType)` where `someType` is a subtype of the bound or current promoted bound of `T`, would promote `T` to `T extends someType` on the true branch, just like we currently promote normal variables. (Since type variables are always final, we won't even have to check that it's not modified anywhere).

Such a promoted type variable can be passed as a type argument to something with a stricter bound than the original.
It cannot be reified at run-time, but a `[]` would *statically* be known to be a `List` as well (so a `List`).

Maybe we can even allow super-bounds. A test of `if (List <: T)` would promote `T` to `T super List` and allow a `List` to be assigned to `T` in the promoted (demoted?) scope. Just as for sub-type promotion, we would have to promote only in a way that doesn't lose previous promotions. So, if we do `if (int <: T && Future <: T) ...`, the latter would not be able to promote because there is no subtype relation between `int` and `Future`.

Contributor guide

Open the contributing guide

Research direction

Start with the proposal in this issue, especially the subtype- and super-bound cases, and compare them with the existing promotion rules for local variables. No file or test entry point is named; done would require a settled, implementable design for type-variable promotion and its type-comparison syntax.

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
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.