Diagnostic for #136932 width limit

#136932 set an upper limit for the width of fields in a format string. It's a very high limit, but it's a lower limit than the compiler allows, and this creates a footgun where if the width is dynamic then your code may compile without warnings and pass your tests but unexpectedly panic for some inputs.

I agree that println!("{a:9999999}") doesn't normally make sense. It's great that this code generates a compiler error, but it's not great that println!("{a:width$}, width=9999999) panics. I haven't gone through and read all the history, but I'm guessing it was determined that the type accepted by the macro can't be changed to u16 because it would break code like let width: u32 = "1234".parse().unwrap(); println!("{a:width$}").

Could the compiler (or maybe Clippy) generate a diagnostic if the value being passed to width is of a type that cannot be coerced to u16 and suggest something like println!("{a:width$}", width=width as u16)? Maybe a future Rust edition can make this into an error by changing the type to u16.

3 Likes

If there is a potential panic, the code likely also optimises less well. (I have not checked this case, but it is often the case.) So it would be good to have at least a clippy lint about this.

2 Likes

I looked into at least improving the panic message, but that'd require a const panic to include runtime information, so that won't work.