Crate pw_format

source ·
Expand description

The pw_format crate is a parser used to implement proc macros that:

  • Understand format string argument types at compile time.
  • Syntax check format strings.

pw_format is written against std and is not intended to be used in an embedded context. Some efficiency and memory is traded for a more expressive interface that exposes the format string’s “syntax tree” to the API client.

§Proc Macros

The macros module provides infrastructure for implementing proc macros that take format strings as arguments.

§Example

use pw_format::{
    Alignment, Argument, ConversionSpec, Flag, FormatFragment, FormatString,
    Length, MinFieldWidth, Precision, Primitive, Style,
};

let format_string =
  FormatString::parse_printf("long double %+ 4.2Lf is %-03hd%%.").unwrap();

assert_eq!(format_string, FormatString {
  fragments: vec![
      FormatFragment::Literal("long double ".to_string()),
      FormatFragment::Conversion(ConversionSpec {
          argument: Argument::None,
          fill: ' ',
          alignment: Alignment::None,
          flags: [Flag::ForceSign, Flag::SpaceSign].into_iter().collect(),
          min_field_width: MinFieldWidth::Fixed(4),
          precision: Precision::Fixed(2),
          length: Some(Length::LongDouble),
          primitive: Primitive::Float,
          style: Style::None,
      }),
      FormatFragment::Literal(" is ".to_string()),
      FormatFragment::Conversion(ConversionSpec {
          argument: Argument::None,
          fill: ' ',
          alignment: Alignment::Left,
          flags: [Flag::LeftJustify, Flag::LeadingZeros]
              .into_iter()
              .collect(),
          min_field_width: MinFieldWidth::Fixed(3),
          precision: Precision::None,
          length: Some(Length::Short),
          primitive: Primitive::Integer,
          style: Style::None,
      }),
      FormatFragment::Literal("%.".to_string()),
  ]
});

Modules§

  • The macro module provides helpers that simplify writing proc macros that take format strings and arguments. This is accomplish with three main constructs:

Structs§

Enums§

  • A core::fmt alignment spec.
  • An argument in a core::fmt style alignment spec.
  • A printf flag (the ‘+’ in %+d).
  • A fragment of a printf format string.
  • A printf length (the l in %ld).
  • A printf minimum field width (the 5 in %5d).
  • A printf precision (the .5 in %.5d).
  • Primitive type of a conversion (integer, float, string, etc.)
  • The abstract formatting style for a conversion.