]> git.lizzy.rs Git - rust.git/blob - src/test/ui/consts/trait_specialization.rs
Merge commit '2bb3996244cf1b89878da9e39841e9f6bf061602' into sync_cg_clif-2022-12-14
[rust.git] / src / test / ui / consts / trait_specialization.rs
1 // ignore-wasm32-bare which doesn't support `std::process:exit()`
2 // compile-flags: -Zmir-opt-level=3
3 // run-pass
4
5 // Tests that specialization does not cause optimizations running on polymorphic MIR to resolve
6 // to a `default` implementation.
7
8 #![feature(specialization)] //~ WARN the feature `specialization` is incomplete
9
10 trait Marker {}
11
12 trait SpecializedTrait {
13     const CONST_BOOL: bool;
14     const CONST_STR: &'static str;
15     fn method() -> &'static str;
16 }
17 impl <T> SpecializedTrait for T {
18     default const CONST_BOOL: bool = false;
19     default const CONST_STR: &'static str = "in default impl";
20     #[inline(always)]
21     default fn method() -> &'static str {
22         "in default impl"
23     }
24 }
25 impl <T: Marker> SpecializedTrait for T {
26     const CONST_BOOL: bool = true;
27     const CONST_STR: &'static str = "in specialized impl";
28     fn method() -> &'static str {
29         "in specialized impl"
30     }
31 }
32
33 fn const_bool<T>() -> &'static str {
34     if <T as SpecializedTrait>::CONST_BOOL {
35         "in specialized impl"
36     } else {
37         "in default impl"
38     }
39 }
40 fn const_str<T>() -> &'static str {
41     <T as SpecializedTrait>::CONST_STR
42 }
43 fn run_method<T>() -> &'static str {
44     <T as SpecializedTrait>::method()
45 }
46
47 struct TypeA;
48 impl Marker for TypeA {}
49 struct TypeB;
50
51 #[inline(never)]
52 fn exit_if_not_eq(left: &str, right: &str) {
53     if left != right {
54         std::process::exit(1);
55     }
56 }
57
58 pub fn main() {
59     exit_if_not_eq("in specialized impl", const_bool::<TypeA>());
60     exit_if_not_eq("in default impl", const_bool::<TypeB>());
61     exit_if_not_eq("in specialized impl", const_str::<TypeA>());
62     exit_if_not_eq("in default impl", const_str::<TypeB>());
63     exit_if_not_eq("in specialized impl", run_method::<TypeA>());
64     exit_if_not_eq("in default impl", run_method::<TypeB>());
65 }