1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use core::ops::{Neg, Not};
macro_rules! doc {
($( $x:expr, )* @$item:item) => {
$( #[doc = $x] )*
$item
};
}
macro_rules! def {
($Op:ident, $RefOp:ident, $op:ident, $ref_op:ident, $assert:expr) => {
doc!(
"An escape hatch for implimenting",
concat!("`", stringify!($Op), "`"),
"for references to newtypes.",
"",
"As of Rust 1.52.1, the following code does not compile:",
"```compile_fail",
concat!("use core::ops::", stringify!($Op), ";"),
"",
"#[derive(PartialEq)]",
"struct A<T>(T);",
"",
concat!("impl<'a, T> ", stringify!($Op), " for &'a A<T>"),
"where",
concat!(" T: ", stringify!($Op), ","),
concat!(" &'a T: ", stringify!($Op), "<Output = T::Output>,"),
"{",
concat!(" type Output = A<T::Output>;"),
"",
concat!(" fn ", stringify!($op), "(self) -> Self::Output {"),
concat!(" A(self.0.", stringify!($op), "())"),
" }",
"}",
"",
"fn f<T>(a: T)",
"where",
concat!(" for<'a> &'a T: ", stringify!($Op), ","),
"{",
concat!(" let ", stringify!($op), "_a = (&a).", stringify!($op), "();"),
"",
concat!(" // to do something with `a` and `", stringify!($op), "_a`"),
" todo!();",
"}",
"",
"fn g<T>(a: T)",
"where",
concat!(" for<'a> &'a T: ", stringify!($Op), ","),
"{",
" f(a);",
"}",
"",
concat!("assert!(", stringify!($assert), ");"),
"```",
"but the following code does:",
"```",
concat!("use core::ops::", stringify!($Op), ";"),
concat!("use ref_ops::", stringify!($RefOp),";"),
"",
"#[derive(PartialEq)]",
"struct A<T>(T);",
"",
concat!("impl<T> ", stringify!($Op), " for &A<T>"),
"where",
concat!(" T: ", stringify!($RefOp), ","),
"{",
" type Output = A<T::Output>;",
"",
concat!(" fn ", stringify!($op), "(self) -> Self::Output {"),
concat!(" A(self.0.", stringify!($ref_op), "())"),
" }",
"}",
"",
"fn f<T>(a: T)",
"where",
concat!(" for<'a> &'a T: ", stringify!($Op), ","),
"{",
concat!(" let ", stringify!($op), "_a = (&a).", stringify!($op), "();"),
"",
concat!(" // to do something with `a` and `", stringify!($op), "_a`"),
" todo!();",
"}",
"",
"fn g<T>(a: T)",
"where",
concat!(" for<'a> &'a T: ", stringify!($Op), ","),
"{",
" f(a);",
"}",
"",
concat!("assert!(", stringify!($assert), ");"),
"```",
@pub trait $RefOp: $Op {
fn $ref_op(&self) -> Self::Output;
}
);
impl<T> $RefOp for T
where
Self: $Op,
for<'a> &'a Self: $Op<Output = Self::Output>,
{
fn $ref_op(&self) -> Self::Output {
self.$op()
}
}
};
}
def!(Neg, RefNeg, neg, ref_neg, -&A(1.0) == A(-1.0));
def!(Not, RefNot, not, ref_not, !&A(true) == A(false));