From cc791ebe60f936355ffa62a53789cc69bcfde7e6 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 10 Apr 2025 11:49:08 +0200 Subject: [PATCH 1/2] Don't allow flattened format_args in const. --- library/core/src/fmt/rt.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/library/core/src/fmt/rt.rs b/library/core/src/fmt/rt.rs index 0459674303d19..754dda9f4ff6f 100644 --- a/library/core/src/fmt/rt.rs +++ b/library/core/src/fmt/rt.rs @@ -174,8 +174,15 @@ impl Argument<'_> { /// let f = format_args!("{}", "a"); /// println!("{f}"); /// ``` + /// + /// This function should _not_ be const, to make sure we don't accept + /// format_args!() and panic!() with arguments in const, even when not evaluated: + /// + /// ```compile_fail,E0015 + /// const _: () = if false { panic!("a {}", "a") }; + /// ``` #[inline] - pub const fn none() -> [Self; 0] { + pub fn none() -> [Self; 0] { [] } } From 56426db0b634fcd8d7e5842f39593651a594e602 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Wed, 30 Apr 2025 13:18:21 +0200 Subject: [PATCH 2/2] Add test for format_args!("{}", 0) in const. --- tests/ui/consts/const-eval/format.rs | 5 +++++ tests/ui/consts/const-eval/format.stderr | 10 +++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/ui/consts/const-eval/format.rs b/tests/ui/consts/const-eval/format.rs index 1878fc0382767..a8085a786e189 100644 --- a/tests/ui/consts/const-eval/format.rs +++ b/tests/ui/consts/const-eval/format.rs @@ -9,4 +9,9 @@ const fn print() { //~| ERROR cannot call non-const function `_print` in constant functions } +const fn format_args() { + format_args!("{}", 0); + //~^ ERROR cannot call non-const formatting macro in constant functions +} + fn main() {} diff --git a/tests/ui/consts/const-eval/format.stderr b/tests/ui/consts/const-eval/format.stderr index e8d7bbcea0917..4c4cbb372a7fd 100644 --- a/tests/ui/consts/const-eval/format.stderr +++ b/tests/ui/consts/const-eval/format.stderr @@ -24,6 +24,14 @@ LL | println!("{:?}", 0); = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants = note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 3 previous errors +error[E0015]: cannot call non-const formatting macro in constant functions + --> $DIR/format.rs:13:5 + | +LL | format_args!("{}", 0); + | ^^^^^^^^^^^^^^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0015`.