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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! Debugging utilities
//!
//! Implement `DebugWith<Cx>` for your type. Then, when using
//! `debug!` or whatever, do `debug!("{}", foo.debug_with(cx))`.

#![feature(box_patterns)]
#![feature(never_type)]
#![feature(in_band_lifetimes)]
#![feature(specialization)]

/// A `Debug` trait that carries a context. Most types in Lark
/// implement it, and you can use `derive(DebugWith)` to get
/// Debug-like behavior (from the lark-debug-derive crate).
///
/// To use it, do something like `format!("{}",
/// value.debug_with(cx))`.
pub trait DebugWith {
    fn debug_with<Cx: ?Sized>(&'me self, cx: &'me Cx) -> DebugCxPair<'me, &'me Self, Cx> {
        DebugCxPair { value: self, cx }
    }

    fn into_debug_with<Cx: ?Sized>(self, cx: &'me Cx) -> DebugCxPair<'me, Self, Cx>
    where
        Self: Sized,
    {
        DebugCxPair { value: self, cx }
    }

    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}

/// Useful trait for writing `DebugWith` implementations that are
/// specialized to different contexts. Just derive `Debug` and use the
/// macro `debug_specialized_impl`; then you can implement
/// `FmtWithSpecialized<Cx>` for various specialized contexts as you
/// choose.
pub trait FmtWithSpecialized<Cx: ?Sized> {
    fn fmt_with_specialized(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}

impl<Cx: ?Sized, T: ?Sized> FmtWithSpecialized<Cx> for T
where
    T: std::fmt::Debug,
{
    default fn fmt_with_specialized(
        &self,
        _cx: &Cx,
        fmt: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        <T as std::fmt::Debug>::fmt(self, fmt)
    }
}

pub struct DebugCxPair<'me, Value, Cx: ?Sized>
where
    Value: DebugWith,
{
    value: Value,
    cx: &'me Cx,
}

impl<Value, Cx: ?Sized> std::fmt::Debug for DebugCxPair<'me, Value, Cx>
where
    Value: DebugWith,
{
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt_with(self.cx, fmt)
    }
}

impl<Value, Cx: ?Sized> std::fmt::Display for DebugCxPair<'me, Value, Cx>
where
    Value: DebugWith,
{
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt_with(self.cx, fmt)
    }
}

impl<T> DebugWith for Vec<T>
where
    T: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_list()
            .entries(self.iter().map(|elem| elem.debug_with(cx)))
            .finish()
    }
}

impl DebugWith for () {
    fn fmt_with<Cx: ?Sized>(
        &self,
        _cx: &Cx,
        fmt: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        <() as std::fmt::Debug>::fmt(self, fmt)
    }
}

impl<A, B> DebugWith for (A, B)
where
    A: DebugWith,
    B: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_tuple("")
            .field(&self.0.debug_with(cx))
            .field(&self.1.debug_with(cx))
            .finish()
    }
}

impl<A, B, C> DebugWith for (A, B, C)
where
    A: DebugWith,
    B: DebugWith,
    C: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_tuple("")
            .field(&self.0.debug_with(cx))
            .field(&self.1.debug_with(cx))
            .field(&self.2.debug_with(cx))
            .finish()
    }
}

impl<A, B, C, D> DebugWith for (A, B, C, D)
where
    A: DebugWith,
    B: DebugWith,
    C: DebugWith,
    D: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_tuple("")
            .field(&self.0.debug_with(cx))
            .field(&self.1.debug_with(cx))
            .field(&self.2.debug_with(cx))
            .field(&self.3.debug_with(cx))
            .finish()
    }
}

impl<T> DebugWith for &T
where
    T: ?Sized + DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        T::fmt_with(self, cx, fmt)
    }
}

impl<T> DebugWith for &mut T
where
    T: ?Sized + DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        T::fmt_with(self, cx, fmt)
    }
}

impl<T> DebugWith for Option<T>
where
    T: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            None => fmt.debug_struct("None").finish(),
            Some(v) => v.fmt_with(cx, fmt),
        }
    }
}

impl<O, E> DebugWith for Result<O, E>
where
    O: DebugWith,
    E: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Ok(v) => fmt.debug_tuple("Ok").field(&v.debug_with(cx)).finish(),
            Err(v) => fmt.debug_tuple("Err").field(&v.debug_with(cx)).finish(),
        }
    }
}

impl<K, V, E> DebugWith for indexmap::IndexMap<K, V, E>
where
    K: DebugWith + std::hash::Hash + Eq,
    V: DebugWith,
    E: std::hash::BuildHasher,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_list()
            .entries(
                self.iter()
                    .map(|elem| (elem.0.into_debug_with(cx), elem.1.into_debug_with(cx))),
            )
            .finish()
    }
}

impl<T> DebugWith for std::sync::Arc<T>
where
    T: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        T::fmt_with(self, cx, fmt)
    }
}

impl<T> DebugWith for Box<T>
where
    T: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        T::fmt_with(self, cx, fmt)
    }
}

impl<T> DebugWith for std::rc::Rc<T>
where
    T: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        T::fmt_with(self, cx, fmt)
    }
}

impl DebugWith for ! {
    fn fmt_with<Cx: ?Sized>(
        &self,
        _cx: &Cx,
        _fmt: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        unreachable!()
    }
}

impl<T> DebugWith for [T]
where
    T: DebugWith,
{
    fn fmt_with<Cx: ?Sized>(&self, cx: &Cx, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.debug_list()
            .entries(self.iter().map(|elem| elem.debug_with(cx)))
            .finish()
    }
}

/// Generates a `DebugWith` impl that accepts any `Cx` and uses the
/// built-in `Debug` trait. You can specialize this to particular
/// contexts by implementing `FmtWithSpecialized<Cx>` to yield a
/// specialized impl.
#[macro_export]
macro_rules! debug_fallback_impl {
    ($(for[$($param:tt)*] $t:ty),* $(,)*) => {
        $(
            impl <$($param)*> $crate::DebugWith for $t {
                default fn fmt_with<Cx: ?Sized>(
                    &self,
                    cx: &Cx,
                    fmt: &mut std::fmt::Formatter<'_>,
                ) -> std::fmt::Result {
                    <$t as $crate::FmtWithSpecialized<Cx>>::fmt_with_specialized(self, cx, fmt)
                }
            }
        )*
    };
    ($($t:ty),* $(,)*) => {
        $crate::debug_fallback_impl!($(for[] $t),*);
    };
}

debug_fallback_impl! {
    i8,
    i16,
    i32,
    i64,
    isize,
    u8,
    u16,
    u32,
    u64,
    usize,
    char,
    bool,
    String,
    str,
}