Skip to content

Commit e7416d5

Browse files
committed
Auto merge of #54317 - Centril:feature/dbg_macro, r=SimonSapin
Implement the dbg!(..) macro Implements the `dbg!(..)` macro due to #54306. cc rust-lang/rfcs#2361 r? @alexcrichton
2 parents 2871872 + e5b9331 commit e7416d5

9 files changed

+332
-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,121 @@
1+
// run-pass
2+
// ignore-cloudabi no processes
3+
// ignore-emscripten no processes
4+
5+
// Tests ensuring that `dbg!(expr)` has the expected run-time behavior.
6+
// as well as some compile time properties we expect.
7+
8+
#![feature(dbg_macro)]
9+
10+
#[derive(Copy, Clone, Debug)]
11+
struct Unit;
12+
13+
#[derive(Copy, Clone, Debug, PartialEq)]
14+
struct Point<T> {
15+
x: T,
16+
y: T,
17+
}
18+
19+
#[derive(Debug, PartialEq)]
20+
struct NoCopy(usize);
21+
22+
fn test() {
23+
let a: Unit = dbg!(Unit);
24+
let _: Unit = dbg!(a);
25+
// We can move `a` because it's Copy.
26+
drop(a);
27+
28+
// `Point<T>` will be faithfully formatted according to `{:#?}`.
29+
let a = Point { x: 42, y: 24 };
30+
let b: Point<u8> = dbg!(Point { x: 42, y: 24 }); // test stringify!(..)
31+
let c: Point<u8> = dbg!(b);
32+
// Identity conversion:
33+
assert_eq!(a, b);
34+
assert_eq!(a, c);
35+
// We can move `b` because it's Copy.
36+
drop(b);
37+
38+
// Test that we can borrow and that successive applications is still identity.
39+
let a = NoCopy(1337);
40+
let b: &NoCopy = dbg!(dbg!(&a));
41+
assert_eq!(&a, b);
42+
43+
// Test involving lifetimes of temporaries:
44+
fn f<'a>(x: &'a u8) -> &'a u8 { x }
45+
let a: &u8 = dbg!(f(&42));
46+
assert_eq!(a, &42);
47+
48+
// Test side effects:
49+
let mut foo = 41;
50+
assert_eq!(7331, dbg!({
51+
foo += 1;
52+
eprintln!("before");
53+
7331
54+
}));
55+
assert_eq!(foo, 42);
56+
}
57+
58+
fn validate_stderr(stderr: Vec<String>) {
59+
assert_eq!(stderr, &[
60+
":23] Unit = Unit",
61+
62+
":24] a = Unit",
63+
64+
":30] Point{x: 42, y: 24,} = Point {",
65+
" x: 42,",
66+
" y: 24",
67+
"}",
68+
69+
":31] b = Point {",
70+
" x: 42,",
71+
" y: 24",
72+
"}",
73+
74+
":40] &a = NoCopy(",
75+
" 1337",
76+
")",
77+
78+
":40] dbg!(& a) = NoCopy(",
79+
" 1337",
80+
")",
81+
":45] f(&42) = 42",
82+
83+
"before",
84+
":50] { foo += 1; eprintln!(\"before\"); 7331 } = 7331",
85+
]);
86+
}
87+
88+
fn main() {
89+
// The following is a hack to deal with compiletest's inability
90+
// to check the output (to stdout) of run-pass tests.
91+
use std::env;
92+
use std::process::Command;
93+
94+
let mut args = env::args();
95+
let prog = args.next().unwrap();
96+
let child = args.next();
97+
if let Some("child") = child.as_ref().map(|s| &**s) {
98+
// Only run the test if we've been spawned as 'child'
99+
test()
100+
} else {
101+
// This essentially spawns as 'child' to run the tests
102+
// and then it collects output of stderr and checks the output
103+
// against what we expect.
104+
let out = Command::new(&prog).arg("child").output().unwrap();
105+
assert!(out.status.success());
106+
assert!(out.stdout.is_empty());
107+
108+
let stderr = String::from_utf8(out.stderr).unwrap();
109+
let stderr = stderr.lines().map(|mut s| {
110+
if s.starts_with("[") {
111+
// Strip `[` and file path:
112+
s = s.trim_start_matches("[");
113+
assert!(s.starts_with(file!()));
114+
s = s.trim_start_matches(file!());
115+
}
116+
s.to_owned()
117+
}).collect();
118+
119+
validate_stderr(stderr);
120+
}
121+
}
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)