Skip to content

Type promotion for this #1397

@eernstg

Description

@eernstg

The reserved word this, when defined, denotes the current instance of the enclosing class, and hence it is known that if this is T yields true then it is sound to promote the static type of this as if this had been a local variable, and similarly for all other situations where the local variable would be promoted.

The promotion of this implies that this gets a different static type (when it is written explicitly, and when it is an implicit part of an instance member access).

class A {
  int a;
  void m() {
    if (this is B) {
      B bb = this; // OK because `this` has type `B`.
      a = b; // OK because it means `this.a = this.b;`.
    }
  }
}

class B extends A {
  int b;
}

However, it is also possible to learn more about type arguments:

class A<X> {
  X x;
  A(this.x);
  void m() {
    if (this is A<int>) {
      x.isEven;
      Iterable<num> xs = [x];
    }
  }
}

class Pair<X, Y> {
  X x; Y y;
  Pair(this.x, this.y);
  void m() {
    if (this is Pair<Y, X>) {
      var tmp = x;
      x = y;
      y = tmp;
    }
  }
}

For simplicity, we could make the choice to support promotion of this with no changes to the treatment of the type parameters of the enclosing class, or with support as an option that we may pursue in the future.

Presumably, it is a nearly non-breaking change to add support for promotion of type parameters, because this only adds more information about said type parameters, it doesn't invalidate existing information. (The change is not completely non-breaking because any change of a static type may give rise to inference of type arguments with different values, and they are reified so the change is observable.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    flow-analysisDiscussions about possible future improvements to flow analysissmall-featureA small feature which is relatively cheap to implement.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions