]> git.lizzy.rs Git - rust.git/commitdiff
Rollup merge of #74056 - fusion-engineering-forks:fmt-arguments-as-str, r=Amanieu
authorManish Goregaokar <manishsmail@gmail.com>
Fri, 17 Jul 2020 21:09:06 +0000 (14:09 -0700)
committerGitHub <noreply@github.com>
Fri, 17 Jul 2020 21:09:06 +0000 (14:09 -0700)
Add Arguments::as_str().

There exist quite a few macros in the Rust ecosystem which use `format_args!()` for formatting, but special case the one-argument case for optimization:

```rust
#[macro_export]
macro_rules! some_macro {
    ($s:expr) => { /* print &str directly, no formatting, no buffers */ };
    ($s:expr, $($tt:tt)*) => { /* use format_args to write to a buffer first */ }
}
```

E.g. [here](https://github.com/rust-embedded/cortex-m-semihosting/blob/7a961f0fbe6eb1b29a7ebde4bad4b9cf5f842b31/src/macros.rs#L48-L58), [here](https://github.com/rust-lang-nursery/failure/blob/20f9a9e223b7cd71aed541d050cc73a747fc00c4/src/macros.rs#L9-L17), and [here](https://github.com/fusion-engineering/px4-rust/blob/7b679cd6da9ffd95f36f6526d88345f8b36121da/px4/src/logging.rs#L45-L52).

The problem with these is that a forgotten argument such as in `some_macro!("{}")` will not be diagnosed, but just prints `"{}"`.

With this PR, it is possible to handle the no-arguments case separately *after* `format_args!()`, while simplifying the macro. Then these macros can give the proper error about a missing argument, just like `print!("{}")` does, while still using the same optimized implementation as before.

This is even more important with [RFC 2795](https://github.com/rust-lang/rfcs/pull/2795), to make sure `some_macro!("{some_variable}")` works as expected.


Trivial merge