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
+42
View File
@@ -0,0 +1,42 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// AUTOUPDATE
// RUN: %{explorer-run}
// RUN: %{explorer-run-trace}
// CHECK:STDOUT: 2
// CHECK:STDOUT: 3
// CHECK:STDOUT: 4
// CHECK:STDOUT: 5
// CHECK:STDOUT: result: 0
package ExplorerTest api;
class A {
var a: i32;
}
class B {
var b: i32;
}
class C {
var c: i32;
}
external impl A as ImplicitAs(B) {
fn Convert[self: Self]() -> B { return {.b = self.a + 1}; }
}
external impl B as As(C) {
fn Convert[self: Self]() -> C { return {.c = self.b + 2}; }
}
fn Main() -> i32 {
var a: (A, A) = ({.a = 1}, {.a = 2});
var b: (B, B) = a;
Print("{0}", b[0].b);
Print("{0}", b[1].b);
var c: (C, C) = b as (C, C);
Print("{0}", c[0].c);
Print("{0}", c[1].c);
return 0;
}
@@ -0,0 +1,27 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// AUTOUPDATE
// RUN: %{not} %{explorer-run}
// RUN: %{not} %{explorer-run-trace}
package ExplorerTest api;
class A {
var a: i32;
}
class B {
var b: i32;
}
external impl A as As(B) {
fn Convert[self: Self]() -> B { return {.b = self.a}; }
}
fn Main() -> i32 {
var a: (i32, A) = (1, {.a = 2});
// CHECK:STDERR: COMPILATION ERROR: {{.*}}/explorer/testdata/tuple/fail_implicit_convert_with_as.carbon:[[@LINE+1]]: type error in name binding: '(i32, class A)' is not implicitly convertible to '(i32, class B)'
var b: (i32, B) = a;
return 0;
}