[ACP] Provide an interface for creating instances of fmt::Formatter · Issue #286 · rust-lang/libs-team (original) (raw)

Edit 2023-10-23: Added a bit of discussion about why a new function on Formatter instead of the builder pattern is problematic

Follow-up to #280.

Proposal

Problem statement

Creating a custom Formatter at runtime as well as modifying an existing Formatter is currently not supported, one can only use the Formatters passed in by the formatting macros. Being able to create and modify them could be useful for multiple use cases:

  1. Calling the formatting code of contained fields with a modified formatting parameter
  2. Exposing different formatting methods for different representations/data points on one struct
  3. Exposing formatting methods that require additional data
  4. Writing libraries that provide enhanced formatting capabilities

Motivating examples or use cases

  1. Allow modifying Formatter members rust#19207
  2. Feature request: Add a way to capture a formatter that can be passed to format helper functions rust#74870
  3. Unable to create Formatter rust#46591
  4. Multiple instances fit this use case:
    • runtime-fmt (a formatting crate that allows the user to supply the format string at runtime) seems to use the unstable fmt_internals feature to build a custom std::fmt::Arguments which has the Formatter baked in (or rather the mostly equivalent fmt::rt::Placeholder struct), see here. In consequence, this crate requires nightly Rust. (Note that the interface isn't the current one as runtime-fmt hasn't been updated since 2019)
    • rt_format (another runtime formatting crate) handles the problem in another way: Using a macro named generate_code!, it generates a function containing a format_args! call for every combination of alignment, signedness, default/alternative representation, zero/space padding, width (via variable), precision (via variable) and formatting trait for a total of 1024 format_args! invocations at the time of writing. Fill characters are not supported, as those cannot be passed via a variable to the format_args! call but must be part of the format specifier. (If you are interested to see the result of this approach, run cargo expand in the crate root and search for a huge function named format_value)
    • I'd like to experiment with a crate that reimplements the formatting macros but adds some additional features (mostly interpolation). However, it is currently impossible to do this in a manner that is compatible with the std implementation outside of nightly Rust (rt_format is almost there, but they cannot support fill characters, apart from their solution being quite hacky and probably inefficient).

Solution sketch

In std::fmt:

struct FormatterBuilder<'a>;
impl<'a> FormatterBuilder<'a> {
    /// Construct a new `FormatterBuilder` with the supplied `Write` trait object for output that is equivalent to the `{}` formatting specifier (no flags, filled with spaces, no alignment, no width, no precision).
    fn new(write: &'a mut (dyn Write + 'a)) -> Self;
    /// Constructs a new `FormatterBuilder` that is equivalent to a given `Formatter`.
    fn new_from_formatter(fmt: &'a mut Formatter<'a>) -> Self
    /// Copies all formatting properties from `other`, only the `Write` trait object is kept
    fn with_formatting_from(mut self, other: &Formatter) -> Self;
    
    fn sign_plus(mut self, sign_plus: bool) -> Self;
    fn sign_minus(mut self, sign_minus: bool) -> Self;
    fn alternate(mut self, alternate: bool) -> Self;
    fn sign_aware_zero_pad(mut self, sign_aware_zero_pad: bool) -> Self;
    fn fill(mut self, fill: char) -> Self;
    fn align(mut self, align: Option<Alignment>) -> Self;
    fn width(mut self, width: Option<usize>) -> Self;
    fn precision(mut self, precision: Option<usize>) -> Self;
    
    /// Builds the `Formatter`.
    fn build(self) -> Formatter<'a>;
}

Note that all FormatterBuilder methods take and return self by value. This is a bit unergonomic, but necessary: build must take self by value in order to transfer ownership of the Write trait object to the returned Formatter.

Alternatives

Relevant previous libs team discussion: rust-lang/rfcs#3394 (comment)
Previous ACP with a different approach: #280

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

Second, if there's a concrete solution: