]> git.lizzy.rs Git - rust.git/blob - src/test/ui/associated-types/defaults-specialization.rs
833981fc8e3c89a2570c55006586394f94a18583
[rust.git] / src / test / ui / associated-types / defaults-specialization.rs
1 //! Tests the interaction of associated type defaults and specialization.
2
3 // compile-fail
4
5 #![feature(associated_type_defaults, specialization)]
6
7 trait Tr {
8     type Ty = u8;
9
10     fn make() -> Self::Ty {
11         0u8
12         //~^ error: mismatched types
13     }
14 }
15
16 struct A<T>(T);
17 // In a `default impl`, assoc. types are defaulted as well,
18 // so their values can't be assumed.
19 default impl<T> Tr for A<T> {
20     fn make() -> u8 { 0 }
21     //~^ ERROR method `make` has an incompatible type for trait
22 }
23
24 struct A2<T>(T);
25 // ...same, but in the method body
26 default impl<T> Tr for A2<T> {
27     fn make() -> Self::Ty { 0u8 }
28     //~^ ERROR mismatched types
29 }
30
31 struct B<T>(T);
32 // Explicitly defaulting the type does the same.
33 impl<T> Tr for B<T> {
34     default type Ty = bool;
35
36     fn make() -> bool { true }
37     //~^ ERROR method `make` has an incompatible type for trait
38 }
39
40 struct B2<T>(T);
41 // ...same, but in the method body
42 impl<T> Tr for B2<T> {
43     default type Ty = bool;
44
45     fn make() -> Self::Ty { true }
46     //~^ ERROR mismatched types
47 }
48
49 struct C<T>(T);
50 // Only the method is defaulted, so this is fine.
51 impl<T> Tr for C<T> {
52     type Ty = bool;
53
54     default fn make() -> bool { true }
55 }
56
57 // Defaulted method *can* assume the type, if the default is kept.
58 struct D<T>(T);
59 impl<T> Tr for D<T> {
60     default fn make() -> u8 { 0 }
61 }
62
63 impl Tr for D<bool> {
64     fn make() -> u8 { 255 }
65 }
66
67 struct E<T>(T);
68 impl<T> Tr for E<T> {
69     default fn make() -> Self::Ty { panic!(); }
70 }
71
72 // This impl specializes and sets `Ty`, it can rely on `Ty=String`.
73 impl Tr for E<bool> {
74     type Ty = String;
75
76     fn make() -> String { String::new() }
77 }
78
79 fn main() {
80     // Test that we can assume the right set of assoc. types from outside the impl
81
82     // This is a `default impl`, which does *not* mean that `A`/`A2` actually implement the trait.
83     // cf. https://github.com/rust-lang/rust/issues/48515
84     //let _: <A<()> as Tr>::Ty = 0u8;
85     //let _: <A2<()> as Tr>::Ty = 0u8;
86
87     let _: <B<()> as Tr>::Ty = 0u8;   //~ error: mismatched types
88     let _: <B<()> as Tr>::Ty = true;  //~ error: mismatched types
89     let _: <B2<()> as Tr>::Ty = 0u8;  //~ error: mismatched types
90     let _: <B2<()> as Tr>::Ty = true; //~ error: mismatched types
91
92     let _: <C<()> as Tr>::Ty = true;
93
94     let _: <D<()> as Tr>::Ty = 0u8;
95     let _: <D<bool> as Tr>::Ty = 0u8;
96 }