-
Notifications
You must be signed in to change notification settings - Fork 205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
More capable Type
objects
#4200
Comments
That sounds like a Kotlin companion object.
Can we have class C {
// Before any static member:
static class extends A.class with HelperMixin1 implements HelperType2;
// Following static members are membes of this static class.
} and you can access the type as You can only extend or implement a
We probably still want to ensure that tear-offs from a static-member type is a canonicalized constant. Somehow. (That's one of the reasons I don't want normal classes to be able to implement the special singleton classes.) To make this equivalent to the current behavior, I assume constructors have access to the type parameters of the (Also, it's currently possible to have
Rather than needing this intersection, just let the generated mixin be
Probably want both a non-static and static type bound, say This will be yet another reason to allow static and instance members with the same name. How will this interact with So, dynamic x;
// ...
... (Object? o) {
...
x = o.runtimeType;
...
...
x.foo(); we may have to retain a lot of static methods that could be tree-shaken today, because we can't tell statically whether they're invoked or not. |
print((int).runtimeType); // _Type
print((int).runtimeType.runtimeType); // _Type
print((String).runtimeType); // _Type But... if (I think, the explanation is that Maybe a function like |
I would say that Then Or maybe that's a bad idea, because of what it does to tree shaking. That is:
A generic type's class objects have instances for each instantiation, and the constructor members can access those. The getters and setters of static variables are not represented by instance variables, they all access the same global variable's state. |
Great comments and questions, @lrhn!
It's similar to Kotlin (and Scala) companion objects, but also different in other ways: I'm not suggesting that Dart classes should stop having the static members and constructors that we know today, I'm just proposing that we should allow developers to request access to some of the static members and constructors (determined by the interface of the This differs from the companion objects in that there is no support for obtaining a companion object from a given actual type argument (because the type argument was erased). In contrast, a Dart type argument will always be able to deliver the corresponding For example: abstract class A<X> { X call(); }
class B1 static implements A<B1> {}
class B2 {}
void main() {
var type = someExpression ? B1 : B2;
if (type is A) {
var newObject = type();
}
} This means that the Kotlin/Scala developer must predict the need to invoke static members or constructors up front (when the concrete type is known) and must pass a reference to the required companion object(s) along with the base data. In contrast, Dart programs can pass type arguments along in the same way they do today, and then it will be possible to get access to the static members and constructors arbitrarily late, as long as the given type is available as the value of a type parameter. In the case where a class does not have a
This seems to imply that we would implicitly generate a static member or a constructor from the instance method implementations. This may or may not be doable, but I'm not quite sure what the desired semantics should be. When it comes to code reuse I would prefer to have good support for forwarding, possibly including some abstraction mechanisms (such that we could introduce sets of forwarding methods rather than specifying them one by one). This could then be used to populate the actual class with actual static members as needed, such that it is able to have the desired
I think the current approach to constants based on constructors and static members is working quite well. The ability to access static members and constructors indirectly via a reified type is an inherently dynamic feature, and I don't think it's useful to try to shoehorn it into a shape where it can yield constant expressions. There's no point in abstracting over something that you already know at compile time anyway.
Good point! Done.
I'm not quite sure what In that case,
A class that doesn't have a A class that does have a static implements clause makes some of its static members and constructors callable from the implicitly generated forwarding instance members, but this is no worse than the following: class A {
static int get foo => 1;
}
class B {
void foo() {
print(A.foo);
}
} We may still be able to detect that With "more capable It may be harder, but it does sound like a task whose complexity is similar to that of tracking invocations of instance members. That is, if we're able to determine that |
@tatumizer wrote:
If you evaluate a type literal (such as In particular, it is certainly possible for an implementation to evaluate Those reified objects may then have different interfaces, that is, they support invocations of different sets of members, so certainly it's possible for On the other hand, the reified There's nothing special about this (and that's basically the point: I want this mechanism to use all the well-known OO mechanisms to provide flexible/abstract access to the static members and constructors which are otherwise oddly inflexible, from an OO perspective).
If we have So we can certainly do abstract interface class MyInterface {
int get foo;
}
class D static implements MyInterface {
static int get foo => 1;
}
void f<X extends D>() {
var reifiedX = X;
if (reifiedX is MyInterface) {
print(reifiedX.foo);
}
} |
Could the following code similar to C#'s syntax: abstract class Json {
static fromJson(Map<String, dynamic> json);
Map<String, dynamic> toJson();
}
class User implements Json { ... } be syntatic sugar for this proposal's syntax? abstract class Json$1 {
Map<String, dynamic> toJson();
}
abstract class Json$2 {
fromJson(Map<String, dynamic> json);
}
class User implements Json$1 static implements Json$2 { ... } To keep EDIT: I can't imagine any piece of code implementing the same interface for instance methods and static methods. However, I can imagine most use cases implementing an interface with instance methods and static methods. That's why I would prefer if instance and static interfaces were merged. |
@eernstg wrote:
This can't be! Today (An argument against |
The That doesn't mean that (I chose Spoiler: void main() {
static(C).static(C.static.static.C).static(C).static;
}
class C {
static C get static => C();
C call(Object? value) => this;
}
C static(Type value) => C();
typedef _C = C;
extension on _C {
_C get static => this;
_C get C => this;
} |
Just to clarify: speaking of Object methods, I didn't mean
That's not the reason to disqualify the word - in practice, it won't hurt anyone. Most people believe Still, it's not clear what |
Class |
If A is a regular class, we can always say Q: Can class say |
Kotlin's companion object model is worth looking into, it won't take long: https://kotlinlang.org/docs/object-declarations.html#companion-objects Main difference is that the companion object has a name and a type, and - most importantly - Kotlin has a word for it, which is (predictably) "companion object". It would be very difficult to even talk about this concept without the word, so I will use it below. The idea is that you can extract a companion object from the object, e.g., (using dart's syntax), I don't know if there's a simple way to express the same concept in dart without introducing the term "companion object". Does anyone have issues with this wording? Interestingly, you very rarely need to extract the companion object explicitly, but the very possibility of doing so explains a lot: it's a real object; consequently, it has a type; this type can extend or implement other types - the whole mental model revolves around the term "companion object". |
@Wdestroier wrote:
abstract class Json {
static fromJson(Map<String, dynamic> json);
Map<String, dynamic> toJson();
}
class User implements Json { ... } Desugared: abstract class Json$1 {
Map<String, dynamic> toJson();
}
abstract class Json$2 {
fromJson(Map<String, dynamic> json);
}
class User implements Json$1 static implements Json$2 { ... } I agree with @mateusfccp that it is going to break the world if a clause like In other words, it's crucial for this proposal that abstract class StaticInterface1 { int get foo; }
abstract class StaticInterface2 { void bar(); }
class B static implements StaticInterface1 {
final int i;
B(this.i);
static int get foo => 10;
}
class C extends B static implements StaticInterface2 {
C(super.i);
static void bar() {}
} This also implies that there is no reason to assume that a type variable void f<X extends Y, Y static extends StaticInterface1>() {
Y.foo; // OK.
X.foo; // Compile-time error, no such member.
} |
I must say I am in love with this proposal. It solves many "problems" at once (although it may introduce more? let's see how the discussion goes), and it's a very interesting concept. I agree that it's not as straightforward to understand it, but once you understand, it makes a lot of sense. I also understand the appeal in having the dynamic and static interfaces bundled together, as @Wdestroier suggests, so if we could come with a non-breaking and viable syntax for doing it (while still providing the base mechanism), I think it would be valuable. |
@tatumizer wrote:
Today If you want to test whether the reified type object for void main() {
var ReifiedString = String; // Obtain the reified type object for the type `String`.
if (ReifiedString is Object) { // Same operation as `String is Object`.
// Here we know that `ReifiedString` is an `Object`, but
// we knew that already, so we can't do anything extra.
ReifiedString.toString(); // Can do, not exciting. ;-)
}
} Testing that It's the instance members of the tested type This means that if The reason why I'm emphasizing that it's all about instance members is that we already have the entire machinery for instance members: Late binding, correct overriding, the works. The static members and the constructors are just used to derive a corresponding instance member that forwards to them, and all the rest occurs in normal object land, with normal OO semantics. |
@eernstg : I understand each of these points, but they don't self-assemble in my head to result in a sense of understanding of the whole. The problem is terminological in nature. See my previous post about Kotlin. |
About Kotlin's companion object, I already mentioned it here. The main point is that you cannot obtain the companion object based on a type argument, you have to denote the concrete class. This reduces the expressive power considerably, because you can pass the type along as a type parameter and you can pass the companion object on as a regular value object, and then you can use the type as a type and the companion object as a way to access static members and constructors of that type. This is tedious because you have to pass the type and the object along your entire call chain whenever you want to use both. You could also pass the type alone, but then you can't get hold of the companion object. Or you could pass the companion object alone, but then you can't use the type (which is highly relevant, e.g., if you're calling constructors). I spelled out how it is possible to write a companion object manually in Dart in this comment. With this proposal, we can obtain the "companion object" (that is, the reified type object) for any given type (type variable or otherwise) by evaluating that type as an expression at any time we want, and we can test whether it satisfies a given interface such that we can call the static members / constructors of that type safely. |
@tatumizer wrote:
The role of the companion object in Kotlin and Scala is played by the reified type object in this proposal. We could of course also introduce an indirection and just add a |
@eernstg : that's where I have to disagree. It's an extra step for cognitive reason, which is a hell of a reason. :-) (Main property of a companion object, apart of its very existence, is that it has a clear type, which is visibly distinct from the type of the object itself, and it's a part of an (explicitly) different hierarchy. The difference is in explicitness). |
If we just use the phrase 'companion object' rather than 'reified type object', would that suffice? I don't think there's any real difference between the members of a companion object in Scala and Kotlin, and the forwarding instance members in this proposal, so the reified type object is the companion object. There is a difference in that this proposal only populates the companion object with forwarding instance members when the target class has a We could also choose to populate every reified type object with all static members and all constructors. However, I suspect that it's a better trade-off to avoid generating so many forwarding methods because (1) they will consume resources (time and space) at least during compilation, and perhaps the unused ones won't be fully tree-shaken, and (2) they aren't recognized by the static type system if the reified type object doesn't have any useful denotable supertypes (so all invocations would then have to be performed dynamically).
Good point! It is indeed an element of implicitness that this proposal works in terms of a 1:1 connection between each targeted static member / constructor and a forwarding instance member of the reified type object. We don't have that kind of relationship anywhere else in the language. The connection is created by specifying exactly how we will take a static member declaration and derive the corresponding instance member signature, and similarly for each constructor. I don't know how this could be made more explicit without asking developers to write a lot of code that would be computed deterministically anyway (which is basically the definition of redundancy). For the type, the |
I don't know if that will suffice, but it would certainly be a step in the right direction. When I see the expression "reified type object", my head refuses to operate further - though I can guess what this means, I'm not sure the guess is correct, and the word "reified" especially scares me off (like, WTF: how this reified type object differs from just type object?). I'll respond to the rest of your comments here later, need time to process :-). |
True, it's important to be an opt-in feature. abstract class MyClass {
// No effect on subtypes.
static String name() => 'MyClass';
// Has effect on subtypes.
abstract MyClass();
// Has effect on subtypes.
abstract static MyClass fromMap(Map<String, dynamic> json) =>
MyConcreteClass(property: json['property']);
} |
Here's an arrangement I could understand:
print(String.companionObject is StringCompanion); // true
print(String.companionObject.runtimeType == StringCompanion); // true This is achieved by adding one method to the Type class: class Type {
Object companionObject; // just an Object
// etc...
}
class Foo<T static implements SomeKnownInterface> {
bar() {
T.companionObject.methodFromKnownInterface(...);
}
}
class Foo static implements FromJson<Foo> {
// no changes to the existing syntax
static Foo fromJson(String str) { ... }
} The companion object will only include the methods from the
The difference of this design and the original one is that, given a type parameter T, you can write WDYT? (Possible alternative for "companionObject": "staticInterfaceObject" or something that contains the word "static") |
Very good! I think I can add a couple of comments here and there to explain why this is just "the same thing with one extra step" compared to my proposal. You may prefer to have that extra step for whatever reason, but I don't think it contributes any extra affordances. Also, I'll try to demystify the notion of a 'reified type object'.
Right, that's exactly what I meant by 'We could of course also introduce an indirection' here.
You'd have to use print((String).companionObject is StringCompanion); // true
print((String).companionObject.runtimeType == StringCompanion); // true But the value of evaluating a type literal like The core idea in this proposal (meaning "the proposal in the first post of this issue") is that this object should (1) have instance members forwarding to the static members and constructors of the type which is being reified, and it should (2) have a type that allows us to call those static members and constructors (indirectly via forwarders) in a type safe manner, without knowing statically that it is exactly the static members and constructors of Returning to To compare, this proposal will do exactly the same thing in the following way (assuming that print(String is Interface); // true
print((String).runtimeType == Interface); // false The second query is false because the run-time type is not exactly
Here's how to do it in this proposal: class Foo<T static implements SomeKnownInterface> {
bar() {
(T).methodFromKnownInterface(...);
}
} The proposal has an extra shortcut: If we encounter
These statements are true for this proposal as well.
The corresponding statement for this proposal is that if the class doesn't declare
In your proposal you can write I hope this illustrates that the two approaches correspond to each other very precisely, and the only difference is that the |
@eernstg: I think I can pinpoint the single place where our views diverge, and it's this: |
Great, I think we're converging!
That's generally not a problem. In my proposal, the RTO for a given class has a type which is a subtype of Currently, we already have a situation where the result returned from the built-in This implies that it isn't a breaking change to make those evaluations yield a result whose type isn't Next step, the static type of an expression that evaluates a type literal that denotes a class/mixin/etc. declaration can include the meta-member mixin. In other words, the static type of This implies that we can safely assign this RTO to a variable with the abstract class StaticFooable { void foo(); }
class A static implements StaticFooable {
static void foo() => print('A.foo');
}
void main() {
StaticFooable companion = A;
companion.foo(); // Prints 'A.foo'.
} However, we can not use an overriding declaration of This means that we don't know anything more specific than It might seem nice and natural if we could make the static interface co-vary with the interface of the base object itself (such that we could use However, note that it would certainly be possible for a type argument to use subsumption in static interface types: abstract class StaticFooable { void foo(); }
abstract class StaticFooBarable implements StaticFooable { void bar(); }
class B extends A static implements StaticFooBarable {
static void foo() => print('B.foo');
static void bar() => print('B.bar');
}
void baz<X static extends StaticFooable>() {
X.foo(); // OK
X.bar(); // Compile-time error, no such member.
(X as dynamic). bar(); // Succeeds when `X` is `B`.
}
void main() {
baz<B>(); // OK, `StaticFooBarable <: StaticFooable` implies that `B is StaticFooable`.
} |
Why do you need this To be sure if we are on the same page, please answer this question. The static type of expression (After re-reading your response, I am not even sure we disagree on anything important, And I do acknowledge the benefits of your proposal, assuming we agree that |
After considering it more, the idea of including in RTO only the references to methods from the declared static interfaces might be unnecessary. Whenever the tree-shaker decides to preserve class C, it will most likely have to preserve its noname constructor, too (otherwise, no one can create an instance). Apart from constructors, the classes rarely have static methods, and those that are potentially used could be identified by name (e.g. if someone says Another point: I think static interfaces don't make much sense. I can't imagine the situation where a class expects type parameter to implement some static methods without also expecting the instances to implement some specific regular methods. abstract class Ring<T> {
abstract T operator+(T other);
abstract T operator*(T other);
// ...etc
abstract static T zero; // SIC!
abstract static T unity;
}
class Integer implements Ring<Integer> {
final int _n;
Integer(this._n);
// ...implementation of operators,
static const zero = Integer(0);
static const unity = Integer(1);
} |
At the risk of this having already been explained and not getting the syntax right, I have a couple questions: abstract class A<X> {
int get foo;
void bar();
X call(int _);
X named(int _, int _);
bool operator==(Object other) {
return other is A && foo == other.foo;
}
}
class B static implements A<B> {
final int i;
B(this.i);
B.named(int i, int j): this(i + j);
static int get foo => 1;
static void bar() {}
}
class C implements A<C> {
const C(this.foo);
@override
final int foo;
@override
void bar() {}
@override
C call(int _) => this;
@override
C named(int _, int _) => this;
}
void main() {
assert(B(0).runtimeType == const C(1));
} would that be legal? And would it be possible for a class to both implement and static implement the same class at the same time? If the name conflict can / could be somehow avoided? And is the override annotation not required / recommended for static implements? sealed class A<X> {
int get foo;
void bar();
X call(int _);
X named(int _, int _);
}
class B static implements A<B> {
final int i;
B(this.i);
B.named(int i, int j): this(i + j);
static int get foo => 1;
static void bar() {}
}
void main() {
final (A) t = B;
final _ = switch(t) {
const (B) _ => print("b"),
// I have to exhaustively check for all classes that static implement A
};
} And would something like that be possible? |
This issue is a response to #356 and other issues requesting virtual static methods or the ability to create a new instance based on a type variable, and similar features.
Static substitutability is hard
The main difficulty with existing proposals in this area is that the set of static members and constructors declared by any given class/mixin/enum/extension type declaration has no interface and no subtype relationships:
As a fundamental OO fact,
B
is an enhanced version ofA
when it comes to instance members (even in this case where we don't enhance anything), but it is simply completely unrelated when it comes to constructors and static members.In particular, the relationship between the constructors
A();
andB();
is very different from an override relationship.A
has a constructor namedA.named
butB
doesn't have a constructor namedB.named
. The static memberB.foo
does not overrideA.foo
.B
does not inheritA.bar
. In general, none of the mechanisms and constraints that allow subtype substitutability when it comes to instance members are available when it comes to "class members" (that is, static members and constructors).Consequently, it would be a massively breaking change to introduce a rule that requires subtype substitutability with respect to class members (apart from the fact that we would need to come up with a precise definition of what that means). This means that it is a highly non-trivial effort to introduce the concept which has been known as a 'static interface' in #356.
This comment mentions the approach which has been taken in C#. This issue suggests going in a different direction that seems like a better match for Dart. The main difference is that the C# approach introduces an actual static interface (static members in an interface that must be implemented by the class that claims to be an implementation of that interface). The approach proposed here transforms the static members into instance members, which means that we immediately have the entire language and all the normal subsumption mechanisms, we don't have to build an entirely new machine for static members.
What's the benefit?
It has been proposed many times, going back to 2013 at least, that an instance of
Type
that reifies a classC
should be able to do a number of things thatC
can do. E.g., if we can doC()
in order to obtain a new instance of the classC
then we should also be able to doMyType()
to obtain such an instance when we havevar MyType = C;
. Similarly forT()
whenT
is a type variable whose value isC
.Another set of requests in this topic area is that static members should be virtual. This is trivially true with this proposal because we're using instance members of the reified
Type
objects to manage the access to the static members.There are several different use cases. A major one is serialization/deserialization where we may frequently need to create instances of a class which is not statically known, and we may wish to call a "virtual static method".
Proposal
We introduce a new kind of type declaration header clause,
static implements
, which is used to indicate that the given declaration must satisfy some subtype-like constraints on the set of static members and constructors.The operand(s) of this clause are regular class/mixin/mixin-class declarations, and the subtype constraints are based on the instance members of these operands. In other words, they are supertypes (of "something"!) in a completely standard way (and the novelty arises because of that "something").
The core idea is that this "something" is a computed set of instance members, amounting to a correct override of each of the instance members of the combined interface of the
static implements
types.These declarations have no compile-time errors. The static analysis notes the
static implements
clause, computes the corresponding meta-member for each static member and for each constructor, and checks that the resulting set of meta-members amount to a correct and complete set of instance members for a class that implementsA<B>
. Here is the set of meta-members (note that they are implicitly created by the tools, not written by a person):The constructor named
B
becomes an instance method namedcall
that takes the same arguments and returns aB
. Similarly, the constructor namedB.named
becomes an instance method namednamed
. Static members become instance members, with the same name and the same signature.The point is that we can now change the result of type
Type
which is returned by evaluatingB
such that it includes this mixin.This implies that for each constructor and static member of
B
, we can call a corresponding instance member of itsType
:This shows that the given
Type
object has the required instance members, and we can use them to get the same effect as that of calling constructors and static members ofB
.We used the type
dynamic
above because those methods are not members of the interface ofType
. However, we could change the typing of type literal expressions such that are not justType
. They could beType & M
in every situation where it is known that the reified type has a given mixinM
. We would then be able to use the following typed approach:Next, we could treat members invoked on type variables specially, such that
T.baz()
means(T).baz()
. This turnsT
into an instance ofType
, which means that we have access to all the meta members of the type. This is a plausible treatment because type variables don't have static members (not even if and when we get static extensions), soT.baz()
is definitely an error today.We would need to consider exactly how to characterize a type variable as having a reified representation that has a certain interface. Perhaps we could use the following:
Even if it turns out to be hard to handle type variables so smoothly, we could of course test it at run time:
Revisions
on Type
.The text was updated successfully, but these errors were encountered: