lazy_panic/
formatter.rs

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
293
294
295
296
297
298
299
300
301
302
//! Formatter module for Panic related messages

#[cfg(feature = "backtrace-on")]
extern crate backtrace;

use std::panic;
use std::io;

///Describes how to write panic's message prefix.
///
///Generally should be simple prefix that will go as `{Prefix}{PanicInfo}...`
pub trait Prefix {
    fn write_in<W: io::Write>(writer: &mut W) -> io::Result<()>;
}

///Describes how to write `PanicInfo`
pub trait PanicInfo {
    fn write_in<W: io::Write>(writer: &mut W, info: &panic::PanicInfo) -> io::Result<()>;
}

///Describes how to write panic's message suffix.
///
///Generally should be simple suffix that will go as `...{PanicInfo}{Suffix}`
pub trait Suffix {
    fn write_in<W: io::Write>(writer: &mut W) -> io::Result<()>;
}

///Describes how to write panic's backtrace
pub trait Backtrace {
    fn write_in<W: io::Write>(writer: &mut W) -> io::Result<()>;
}

///Noop configuration.
///
///Literally does nothing, use it when you want to omit the part
///
///As [PanicFormat](trait.PanicFormat.html) it writes nothing
pub struct Empty;

impl Prefix for Empty {
    #[inline]
    fn write_in<W: io::Write>(_: &mut W) -> io::Result<()> {
        Ok(())
    }
}

impl PanicInfo for Empty {
    #[inline]
    fn write_in<W: io::Write>(_: &mut W, _: &panic::PanicInfo) -> io::Result<()> {
        Ok(())
    }
}

impl Suffix for Empty {
    #[inline]
    fn write_in<W: io::Write>(_: &mut W) -> io::Result<()> {
        Ok(())
    }
}

impl Backtrace for Empty {
    #[inline]
    fn write_in<W: io::Write>(_: &mut W) -> io::Result<()> {
        Ok(())
    }
}

///Simple configuration that should be generic.
///
///For prefix it is constant string `Panic: `
///
///For `PanicInfo` it writes `{file}:{line} - {payload}`
///
///For suffix it is `\n`
///
///For backtrace it is noop
///
///As [PanicFormat](trait.PanicFormat.html) all above together.
pub struct Simple;

impl Prefix for Simple {
    #[inline]
    fn write_in<W: io::Write>(writer: &mut W) -> io::Result<()> {
        writer.write_all("Panic: ".as_bytes())
    }
}

impl PanicInfo for Simple {
    #[inline]
    fn write_in<W: io::Write>(writer: &mut W, info: &panic::PanicInfo) -> io::Result<()> {
        match info.location() {
            Some(location) => write!(writer, "{}:{} - ", location.file(), location.line()),
            None  => write!(writer, "unknown:0 - ")
        }?;
        write_payload!(writer, info.payload(), types: [&str, String])
    }
}

impl Suffix for Simple {
    #[inline]
    fn write_in<W: io::Write>(writer: &mut W) -> io::Result<()> {
        write!(writer, "\n")
    }
}

impl Backtrace for Simple {
    #[inline]
    fn write_in<W: io::Write>(_: &mut W) -> io::Result<()> {
        Ok(())
    }
}

///Panic formatter
///
///Default print method writes each component in following order:
///1. Backtrace
///2. Prefix
///3. `PanicInfo`
///5. Suffix
pub trait PanicFormat {
    type Writer: io::Write;
    type Backtrace: Backtrace;
    type Prefix: Prefix;
    type PanicInfo: PanicInfo;
    type Suffix: Suffix;

    fn writer() -> Self::Writer;

    fn print(info: &panic::PanicInfo) {
        let mut writer = Self::writer();

        let _ = Self::Backtrace::write_in(&mut writer);
        let _ = Self::Prefix::write_in(&mut writer);
        let _ = Self::PanicInfo::write_in(&mut writer, info);
        let _ = Self::Suffix::write_in(&mut writer);
    }
}

impl PanicFormat for Simple {
    type Writer = io::BufWriter<io::Stderr>;
    type Backtrace = Self;
    type Prefix = Self;
    type PanicInfo = Self;
    type Suffix = Self;

    fn writer() -> Self::Writer {
        let stderr = io::stderr();
        io::BufWriter::new(stderr)
    }
}

impl PanicFormat for Empty {
    type Writer = io::Stderr;
    type Backtrace = Self;
    type Prefix = Self;
    type PanicInfo = Self;
    type Suffix = Self;

    fn writer() -> Self::Writer {
        io::stderr()
    }

    fn print(_: &panic::PanicInfo) {
    }
}


///Provides simple output with backtrace
///
///Note that if `backtrace-on` is disabled
///then `Backtrace` is noop
///
///Note: Backtrace output is trimmed to only user's most recent call
///So actual call stack may be longer
pub struct Debug;

impl Backtrace for Debug {
    #[cfg(not(feature = "backtrace-on"))]
    #[inline]
    fn write_in<W: io::Write>(_: &mut W) -> io::Result<()> {
        Ok(())
    }

    #[cfg(feature = "backtrace-on")]
    #[inline]
    fn write_in<W: io::Write>(writer: &mut W) -> io::Result<()> {
        use std::mem;

        //First 3 frames are from backtrace.
        //In middle 3 are from lazy_panic
        //Last 2 are from Rust runtime
        const TRASH_FRAMES_NUM: usize = 8;
        const HEX_WIDTH: usize = mem::size_of::<usize>() + 2;

        let backtrace = self::backtrace::Backtrace::new();
        //By default backtrace includes last function call
        //which means the above new()
        //But we should really trim it down to user panic

        //Code is based on backtrace source
        write!(writer, "Stack backtrace:")?;
        for (idx, frame) in backtrace.frames().iter().skip(TRASH_FRAMES_NUM).enumerate() {
            let ip = frame.ip();
            write!(writer, "\n{:4}: {:2$?}", idx, ip, HEX_WIDTH)?;

            let symbols = frame.symbols();
            if symbols.len() == 0 {
                write!(writer, " - <unresolved>")?;
            }

            for (idx, symbol) in symbols.iter().enumerate() {
                if idx != 0 {
                    write!(writer, "\n      {:1$}", "", HEX_WIDTH)?;
                }

                if let Some(name) = symbol.name() {
                    write!(writer, " - {}", name)?;
                } else {
                    write!(writer, " - <unknown>")?;
                }

                if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) {
                    write!(writer, "\n      {:3$}at {}:{}", "", file.display(), line, HEX_WIDTH)?;
                }
            }
        }

        write!(writer, "\n")
    }
}

impl PanicFormat for Debug {
    type Writer = io::BufWriter<io::Stderr>;
    type Prefix = Simple;
    type PanicInfo = Simple;
    type Suffix = Simple;
    type Backtrace = Self;

    fn writer() -> Self::Writer {
        let stderr = io::stderr();
        io::BufWriter::new(stderr)
    }
}

///Treats panic as just error
///
///Only panic's payload gets printed to stderr
pub struct JustError;

impl PanicInfo for JustError {
    #[inline]
    fn write_in<W: io::Write>(writer: &mut W, info: &panic::PanicInfo) -> io::Result<()> {
        write_payload!(writer, info.payload(), types: [&str, String])
    }
}

impl PanicFormat for JustError {
    type Writer = io::BufWriter<io::Stderr>;
    type Prefix = Empty;
    type PanicInfo = Self;
    type Suffix = Simple;
    type Backtrace = Empty;

    fn writer() -> Self::Writer {
        let stderr = io::stderr();
        io::BufWriter::new(stderr)
    }
}

#[cfg(test)]
mod tests {
    use super::{Simple, Empty, Debug, JustError};

    #[test]
    #[should_panic]
    fn should_simple_panic() {
        set_panic_message!(Simple);
        panic!("lolka");
    }

    #[test]
    #[should_panic]
    fn should_empty_panic() {
        set_panic_message!(Empty);
        panic!("lolka");
    }

    #[test]
    #[should_panic]
    fn should_debug_panic() {
        set_panic_message!(Debug);
        panic!("lolka");
    }

    #[test]
    #[should_panic]
    fn should_just_error_panic() {
        set_panic_message!(JustError);
        panic!("lolka");
    }

}