Support explicit conversion of tuples. (#2537)

Allow explicit conversion from a tuple of `T1`, `T2`, ... to a tuple of `U1`, `U2`, ... if each element has an explicit conversion.

Also add a comment to existing `ImplicitAs` impl for tuples explaining its purpose.
This commit is contained in:
Richard Smith
2023-01-19 14:56:01 -08:00
committed by GitHub
parent 35989c5283
commit c8f18446f4
3 changed files with 96 additions and 0 deletions
+27
View File
@@ -43,6 +43,7 @@ __match_first {
fn Convert[self: Self]() -> U { return __EqualConvert(self, U); }
}
// A tuple implicitly converts to another tuple if all its elements do.
// TODO: Simplify this once we have variadics.
// TODO: Should these be final?
impl forall [U1:! type, T1:! ImplicitAs(U1)]
@@ -67,6 +68,32 @@ __match_first {
return (v1.Convert(), v2.Convert(), v3.Convert());
}
}
// A tuple explicitly converts to another tuple if all its elements do. Note
// that this fully overlaps with the previous set of impls for the case where
// an implicit conversion is possible.
impl forall [U1:! type, T1:! As(U1)]
(T1,) as As((U1,)) {
fn Convert[self: Self]() -> (U1,) {
let (v1: T1,) = self;
return (v1.Convert(),);
}
}
impl forall [U1:! type, U2:! type, T1:! As(U1), T2:! As(U2)]
(T1, T2) as As((U1, U2)) {
fn Convert[self: Self]() -> (U1, U2) {
let (v1: T1, v2: T2) = self;
return (v1.Convert(), v2.Convert());
}
}
impl forall [U1:! type, U2:! type, U3:! type,
T1:! As(U1), T2:! As(U2), T3:! As(U3)]
(T1, T2, T3) as As((U1, U2, U3)) {
fn Convert[self: Self]() -> (U1, U2, U3) {
let (v1: T1, v2: T2, v3: T3) = self;
return (v1.Convert(), v2.Convert(), v3.Convert());
}
}
}
// ----------------------