Skip to content

Don't allow flattened format_args in const. #139624

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion library/core/src/fmt/rt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
[]
}
}
Expand Down
5 changes: 5 additions & 0 deletions tests/ui/consts/const-eval/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}
10 changes: 9 additions & 1 deletion tests/ui/consts/const-eval/format.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Loading