Skip to content

Commit 3168346

Browse files
authored
Rollup merge of rust-lang#54317 - Centril:feature/dbg_macro, r=SimonSapin
Implement the dbg!(..) macro Implements the `dbg!(..)` macro due to rust-lang#54306. cc rust-lang/rfcs#2361 r? @alexcrichton
2 parents 8a61907 + 924a693 commit 3168346

9 files changed

+330
-0
lines changed

src/libstd/macros.rs

+120
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,126 @@ macro_rules! eprintln {
220220
})
221221
}
222222

223+
/// A macro for quick and dirty debugging with which you can inspect
224+
/// the value of a given expression. An example:
225+
///
226+
/// ```rust
227+
/// #![feature(dbg_macro)]
228+
///
229+
/// let a = 2;
230+
/// let b = dbg!(a * 2) + 1;
231+
/// // ^-- prints: [src/main.rs:4] a * 2 = 4
232+
/// assert_eq!(b, 5);
233+
/// ```
234+
///
235+
/// The macro works by using the `Debug` implementation of the type of
236+
/// the given expression to print the value to [stderr] along with the
237+
/// source location of the macro invocation as well as the source code
238+
/// of the expression.
239+
///
240+
/// Invoking the macro on an expression moves and takes ownership of it
241+
/// before returning the evaluated expression unchanged. If the type
242+
/// of the expression does not implement `Copy` and you don't want
243+
/// to give up ownership, you can instead borrow with `dbg!(&expr)`
244+
/// for some expression `expr`.
245+
///
246+
/// Note that the macro is intended as a debugging tool and therefore you
247+
/// should avoid having uses of it in version control for longer periods.
248+
/// Use cases involving debug output that should be added to version control
249+
/// may be better served by macros such as `debug!` from the `log` crate.
250+
///
251+
/// # Stability
252+
///
253+
/// The exact output printed by this macro should not be relied upon
254+
/// and is subject to future changes.
255+
///
256+
/// # Panics
257+
///
258+
/// Panics if writing to `io::stderr` fails.
259+
///
260+
/// # Further examples
261+
///
262+
/// With a method call:
263+
///
264+
/// ```rust
265+
/// #![feature(dbg_macro)]
266+
///
267+
/// fn foo(n: usize) {
268+
/// if let Some(_) = dbg!(n.checked_sub(4)) {
269+
/// // ...
270+
/// }
271+
/// }
272+
///
273+
/// foo(3)
274+
/// ```
275+
///
276+
/// This prints to [stderr]:
277+
///
278+
/// ```text,ignore
279+
/// [src/main.rs:4] n.checked_sub(4) = None
280+
/// ```
281+
///
282+
/// Naive factorial implementation:
283+
///
284+
/// ```rust
285+
/// #![feature(dbg_macro)]
286+
///
287+
/// fn factorial(n: u32) -> u32 {
288+
/// if dbg!(n <= 1) {
289+
/// dbg!(1)
290+
/// } else {
291+
/// dbg!(n * factorial(n - 1))
292+
/// }
293+
/// }
294+
///
295+
/// dbg!(factorial(4));
296+
/// ```
297+
///
298+
/// This prints to [stderr]:
299+
///
300+
/// ```text,ignore
301+
/// [src/main.rs:3] n <= 1 = false
302+
/// [src/main.rs:3] n <= 1 = false
303+
/// [src/main.rs:3] n <= 1 = false
304+
/// [src/main.rs:3] n <= 1 = true
305+
/// [src/main.rs:4] 1 = 1
306+
/// [src/main.rs:5] n * factorial(n - 1) = 2
307+
/// [src/main.rs:5] n * factorial(n - 1) = 6
308+
/// [src/main.rs:5] n * factorial(n - 1) = 24
309+
/// [src/main.rs:11] factorial(4) = 24
310+
/// ```
311+
///
312+
/// The `dbg!(..)` macro moves the input:
313+
///
314+
/// ```compile_fail
315+
/// #![feature(dbg_macro)]
316+
///
317+
/// /// A wrapper around `usize` which importantly is not Copyable.
318+
/// #[derive(Debug)]
319+
/// struct NoCopy(usize);
320+
///
321+
/// let a = NoCopy(42);
322+
/// let _ = dbg!(a); // <-- `a` is moved here.
323+
/// let _ = dbg!(a); // <-- `a` is moved again; error!
324+
/// ```
325+
///
326+
/// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
327+
#[macro_export]
328+
#[unstable(feature = "dbg_macro", issue = "54306")]
329+
macro_rules! dbg {
330+
($val:expr) => {
331+
// Use of `match` here is intentional because it affects the lifetimes
332+
// of temporaries - https://stackoverflow.com/a/48732525/1063961
333+
match $val {
334+
tmp => {
335+
eprintln!("[{}:{}] {} = {:#?}",
336+
file!(), line!(), stringify!($val), &tmp);
337+
tmp
338+
}
339+
}
340+
}
341+
}
342+
223343
#[macro_export]
224344
#[unstable(feature = "await_macro", issue = "50547")]
225345
#[allow_internal_unstable]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// run-pass
2+
3+
// Tests ensuring that `dbg!(expr)` has the expected run-time behavior.
4+
// as well as some compile time properties we expect.
5+
6+
#![feature(dbg_macro)]
7+
8+
#[derive(Copy, Clone, Debug)]
9+
struct Unit;
10+
11+
#[derive(Copy, Clone, Debug, PartialEq)]
12+
struct Point<T> {
13+
x: T,
14+
y: T,
15+
}
16+
17+
#[derive(Debug, PartialEq)]
18+
struct NoCopy(usize);
19+
20+
fn test() {
21+
let a: Unit = dbg!(Unit);
22+
let _: Unit = dbg!(a);
23+
// We can move `a` because it's Copy.
24+
drop(a);
25+
26+
// `Point<T>` will be faithfully formatted according to `{:#?}`.
27+
let a = Point { x: 42, y: 24 };
28+
let b: Point<u8> = dbg!(Point { x: 42, y: 24 }); // test stringify!(..)
29+
let c: Point<u8> = dbg!(b);
30+
// Identity conversion:
31+
assert_eq!(a, b);
32+
assert_eq!(a, c);
33+
// We can move `b` because it's Copy.
34+
drop(b);
35+
36+
// Test that we can borrow and that successive applications is still identity.
37+
let a = NoCopy(1337);
38+
let b: &NoCopy = dbg!(dbg!(&a));
39+
assert_eq!(&a, b);
40+
41+
// Test involving lifetimes of temporaries:
42+
fn f<'a>(x: &'a u8) -> &'a u8 { x }
43+
let a: &u8 = dbg!(f(&42));
44+
assert_eq!(a, &42);
45+
46+
// Test side effects:
47+
let mut foo = 41;
48+
assert_eq!(7331, dbg!({
49+
foo += 1;
50+
eprintln!("before");
51+
7331
52+
}));
53+
assert_eq!(foo, 42);
54+
}
55+
56+
fn validate_stderr(stderr: Vec<String>) {
57+
assert_eq!(stderr, &[
58+
":21] Unit = Unit",
59+
60+
":22] a = Unit",
61+
62+
":28] Point{x: 42, y: 24,} = Point {",
63+
" x: 42,",
64+
" y: 24",
65+
"}",
66+
67+
":29] b = Point {",
68+
" x: 42,",
69+
" y: 24",
70+
"}",
71+
72+
":38] &a = NoCopy(",
73+
" 1337",
74+
")",
75+
76+
":38] dbg!(& a) = NoCopy(",
77+
" 1337",
78+
")",
79+
":43] f(&42) = 42",
80+
81+
"before",
82+
":48] { foo += 1; eprintln!(\"before\"); 7331 } = 7331",
83+
]);
84+
}
85+
86+
fn main() {
87+
// The following is a hack to deal with compiletest's inability
88+
// to check the output (to stdout) of run-pass tests.
89+
use std::env;
90+
use std::process::Command;
91+
92+
let mut args = env::args();
93+
let prog = args.next().unwrap();
94+
let child = args.next();
95+
if let Some("child") = child.as_ref().map(|s| &**s) {
96+
// Only run the test if we've been spawned as 'child'
97+
test()
98+
} else {
99+
// This essentially spawns as 'child' to run the tests
100+
// and then it collects output of stderr and checks the output
101+
// against what we expect.
102+
let out = Command::new(&prog).arg("child").output().unwrap();
103+
assert!(out.status.success());
104+
assert!(out.stdout.is_empty());
105+
106+
let stderr = String::from_utf8(out.stderr).unwrap();
107+
let stderr = stderr.lines().map(|mut s| {
108+
if s.starts_with("[") {
109+
// Strip `[` and file path:
110+
s = s.trim_start_matches("[");
111+
assert!(s.starts_with(file!()));
112+
s = s.trim_start_matches(file!());
113+
}
114+
s.to_owned()
115+
}).collect();
116+
117+
validate_stderr(stderr);
118+
}
119+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// Feature gate test for `dbg!(..)`.
2+
3+
fn main() {
4+
dbg!(1);
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0658]: macro dbg! is unstable (see issue #54306)
2+
--> $DIR/dbg-macro-feature-gate.rs:4:5
3+
|
4+
LL | dbg!(1);
5+
| ^^^^^^^^
6+
|
7+
= help: add #![feature(dbg_macro)] to the crate attributes to enable
8+
9+
error: aborting due to previous error
10+
11+
For more information about this error, try `rustc --explain E0658`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
error[E0382]: use of moved value: `a`
2+
--> $DIR/dbg-macro-move-semantics.rs:11:18
3+
|
4+
LL | let _ = dbg!(a);
5+
| ------- value moved here
6+
LL | let _ = dbg!(a);
7+
| ^ value used here after move
8+
|
9+
= note: move occurs because `a` has type `NoCopy`, which does not implement the `Copy` trait
10+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
11+
12+
error: aborting due to previous error
13+
14+
For more information about this error, try `rustc --explain E0382`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Test ensuring that `dbg!(expr)` will take ownership of the argument.
2+
3+
#![feature(dbg_macro)]
4+
5+
#[derive(Debug)]
6+
struct NoCopy(usize);
7+
8+
fn main() {
9+
let a = NoCopy(0);
10+
let _ = dbg!(a);
11+
let _ = dbg!(a);
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
error[E0382]: use of moved value: `a`
2+
--> $DIR/dbg-macro-move-semantics.rs:11:18
3+
|
4+
LL | let _ = dbg!(a);
5+
| ------- value moved here
6+
LL | let _ = dbg!(a);
7+
| ^ value used here after move
8+
|
9+
= note: move occurs because `a` has type `NoCopy`, which does not implement the `Copy` trait
10+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
11+
12+
error[E0382]: use of moved value: `a`
13+
--> $DIR/dbg-macro-move-semantics.rs:11:13
14+
|
15+
LL | let _ = dbg!(a);
16+
| ------- value moved here
17+
LL | let _ = dbg!(a);
18+
| ^^^^^^^ value used here after move
19+
|
20+
= note: move occurs because `a` has type `NoCopy`, which does not implement the `Copy` trait
21+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
22+
23+
error: aborting due to 2 previous errors
24+
25+
For more information about this error, try `rustc --explain E0382`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Test ensuring that `dbg!(expr)` requires the passed type to implement `Debug`.
2+
3+
#![feature(dbg_macro)]
4+
5+
struct NotDebug;
6+
7+
fn main() {
8+
let _: NotDebug = dbg!(NotDebug);
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0277]: `NotDebug` doesn't implement `std::fmt::Debug`
2+
--> $DIR/dbg-macro-requires-debug.rs:8:23
3+
|
4+
LL | let _: NotDebug = dbg!(NotDebug);
5+
| ^^^^^^^^^^^^^^ `NotDebug` cannot be formatted using `{:?}`
6+
|
7+
= help: the trait `std::fmt::Debug` is not implemented for `NotDebug`
8+
= note: add `#[derive(Debug)]` or manually implement `std::fmt::Debug`
9+
= note: required because of the requirements on the impl of `std::fmt::Debug` for `&NotDebug`
10+
= note: required by `std::fmt::Debug::fmt`
11+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)