Rollup merge of #152508 - arferreira:improve-write-macro-diagnostic, r=Mark-Simulacrum

Improve write! and writeln! error when called without destination

Fixes rust-lang/rust#152493

Adds catch-all arms to `write!` and `writeln!` macros so that calling them without a destination (e.g., `write!("S")` instead of `write!(f, "S")`) gives a clear error instead of the cryptic "unexpected end of macro invocation" pointing at macro internals.

r? @estebank
This commit is contained in:
Jacob Pratt 2026-02-14 23:17:31 -05:00 committed by GitHub
commit 8075b89aa6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 21 additions and 0 deletions

View file

@ -607,6 +607,9 @@ macro_rules! write {
($dst:expr, $($arg:tt)*) => {
$dst.write_fmt($crate::format_args!($($arg)*))
};
($($arg:tt)*) => {
compile_error!("requires a destination and format arguments, like `write!(dest, \"format string\", args...)`")
};
}
/// Writes formatted data into a buffer, with a newline appended.
@ -645,6 +648,9 @@ macro_rules! writeln {
($dst:expr, $($arg:tt)*) => {
$dst.write_fmt($crate::format_args_nl!($($arg)*))
};
($($arg:tt)*) => {
compile_error!("requires a destination and format arguments, like `writeln!(dest, \"format string\", args...)`")
};
}
/// Indicates unreachable code.

View file

@ -0,0 +1,7 @@
// Check that `write!` without a destination gives a helpful error message.
// See https://github.com/rust-lang/rust/issues/152493
fn main() {
write!("S");
//~^ ERROR requires a destination and format arguments
}

View file

@ -0,0 +1,8 @@
error: requires a destination and format arguments, like `write!(dest, "format string", args...)`
--> $DIR/write-missing-destination.rs:5:5
|
LL | write!("S");
| ^^^^^^^^^^^
error: aborting due to 1 previous error