7 releases (4 breaking)

0.4.0 Jun 27, 2023
0.3.0 Apr 24, 2023
0.2.2 Apr 8, 2023
0.1.0 Jun 23, 2021
0.0.0 Aug 18, 2020

#217 in Procedural macros

32 downloads per month

MIT license

38KB
811 lines

fv-template

Rust Latest version Documentation Latest

Getting started

In your proc-macro crate, you can add fv-template as a dependency. Consumers of your proc-macros don't need to depend on fv-template themselves.

For details on what field-value templates are and why you might want to use them, see the docs.

How do I use it?

This library is intended to be used by proc-macro authors, like emit. It doesn't define any macros of its own.

See the examples directory for a sample that uses fv-template in a proc-macro and a consuming application.


lib.rs:

Compile-time support for interpolated string templates using field-value expressions.

Field-value templates

A field-value template is a string literal surrounded by field-value expressions:

a, b: 42, "Some text {c} and {d: true}", e, f: "text"
───┬────  ───────────────┬─────────────  ──────┬─────
before literal           literal             after literal

The template string literal consists of blocks of text with holes between braces, where the value in a hole is a field-value expression:

"Some text {c} and {d: true}"
─┬─     ────┬────
└────┬─────┘
hole

"Some text {c} and {d: true}"
─────┬────   ──┬──
└────┬────┘
text

The syntax is similar to Rust's format_args! macro, but leans entirely on standard field-value expressions for specifying values to interpolate.

Why not format_args!?

Rust's format_args! macro already defines a syntax for string interpolation, but isn't suitable for all situations:

  • It's core purpose is to build strings. format_args! is based on machinery that throws away type-specific information eagerly. It also performs optimizations at compile time that inline certain values into the builder.
  • It doesn't have a programmatic API. You can only make assumptions about how a format_args! invocation will behave by observing the syntactic tokens passed to it at compile-time. You don't get any visibility into the format literal itself.
  • Flags are compact for formatting, but don't scale. The :?#<> tokens used for customizing formatting are compact, but opaque, and don't naturally allow for arbitrarily complex annotation like attributes do.

When any of those trade-offs in format_args! becomes a problem, field-value templates may be a solution.

Dependencies

~310–760KB
~18K SLoC