From cb653b100c43118beed5bbd84cd8b832362a355f Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Mon, 15 Feb 2021 21:06:00 -0500 Subject: [PATCH 1/2] Document that `assert!` format arguments are evaluated lazily It can be useful to do some computation in `assert!` format arguments, in order to get better error messages. For example: ```rust assert!( some_condition, "The state is invalid. Details: {}", expensive_call_to_get_debugging_info(), ); ``` It seems like `assert!` only evaluates the format arguments if the assertion fails, which is useful but doesn't appear to be documented anywhere. This PR documents the behavior and adds some tests. --- library/core/src/macros/mod.rs | 3 ++- src/test/ui/macros/assert-format-lazy.rs | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/macros/assert-format-lazy.rs diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 7aaf5a5fd4614..3b085b0459a4f 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -1208,7 +1208,8 @@ pub(crate) mod builtin { /// /// This macro has a second form, where a custom panic message can /// be provided with or without arguments for formatting. See [`std::fmt`] - /// for syntax for this form. + /// for syntax for this form. Expressions used as format arguments will only + /// be evaluated if the assertion fails. /// /// [`std::fmt`]: ../std/fmt/index.html /// diff --git a/src/test/ui/macros/assert-format-lazy.rs b/src/test/ui/macros/assert-format-lazy.rs new file mode 100644 index 0000000000000..e0e2bd5a970e5 --- /dev/null +++ b/src/test/ui/macros/assert-format-lazy.rs @@ -0,0 +1,11 @@ +// run-pass + +#[allow(unreachable_code)] +fn main() { + assert!(true, "Failed: {:?}", panic!("assert! evaluated format expressions")); + debug_assert!(true, "Failed: {:?}", panic!("debug_assert! evaluated format expressions")); + assert_eq!(1, 1, "Failed: {:?}", panic!("assert_eq! evaluated format expressions")); + debug_assert_eq!(1, 1, "Failed: {:?}", panic!("debug_assert_eq! evaluated format expressions")); + assert_ne!(1, 2, "Failed: {:?}", panic!("assert_ne! evaluated format expressions")); + debug_assert_ne!(1, 2, "Failed: {:?}", panic!("debug_assert_ne! evaluated format expressions")); +} From 15197cbc61450bd19328387ad9a04500e35d7086 Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Tue, 16 Feb 2021 19:05:30 -0500 Subject: [PATCH 2/2] Ensure debug_assert! tests get run --- src/test/ui/macros/assert-format-lazy.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/ui/macros/assert-format-lazy.rs b/src/test/ui/macros/assert-format-lazy.rs index e0e2bd5a970e5..c7f05d763b7a4 100644 --- a/src/test/ui/macros/assert-format-lazy.rs +++ b/src/test/ui/macros/assert-format-lazy.rs @@ -1,4 +1,5 @@ // run-pass +// compile-flags: -C debug_assertions=yes #[allow(unreachable_code)] fn main() {