rules_derive 0.1.0

simple and fast derive macros using macro_rules
Documentation
  • Coverage
  • 100%
    4 out of 4 items documented1 out of 3 items with examples
  • Size
  • Source code size: 71.21 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 408.89 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 3s Average build duration of successful builds.
  • all releases: 3s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Repository
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • reinerp

rules_derive: simple and fast derive macros using macro_rules

This library allows you to define custom deriving instances using macro_rules! macros rather than proc-macros. This is often much simpler.

Getting started

Define a deriving macro with macro_rules!():

macro_rules! MyTrait {
  (/* see `rules_derive` for definition of signature */) => {
    // Generate impl
    impl $($generics_bindings)* MyTrait for $ty where $($generics_where)* {
      // implementation here
    }
  }
}

Then use it under the rules_derive attribute:

#[rules_derive(MyTrait)]
struct MyType { x: u32, y: String }

The macro definition can be in the same crate or file as its use.

See full examples in the examples directory.

Tutorial

See the announcement blog post for a tutorial.

Parsed syntax

The rules_derive macro parses any enum/struct definition into a simpler-to-parse format, which it then passes to your macro. The primary transformations it does are:

  • Convert all enum/struct syntaxes and named-field/unnamed-field/unit syntaxes into a uniform sum-of-products syntax.
  • Convert any generic parameters in the typical ways needed for impl headers.

The motivation for these transformations is given in the announcement blog post. Here is an example of the effect of this transformation:

// Rust type definition:
#[rustfmt::skip]
pub enum Foo<T: Clone = u8> where u8: Into<T> { 
    A { x: T },
    B,
    C(u8),
}

// rules_derive-transformed type definition:
((#[rustfmt::skip])) 
pub enum Foo((Foo<T>) (<T: Clone>) where (u8: Into<T>,))
{
    A(named Foo::A) { field__x @ x : T, } 
    B(unit Foo::B) {}
    C(unnamed Foo::C) { field__0 @ 0 : u8, }
}

This transformed type definition is then passed to your macro. You can see the macro_rules! header that accepts this transformed type definition on the [rules_derive] documentation.