5 releases

0.2.0 Mar 30, 2024
0.1.5 Mar 20, 2021
0.1.3 Dec 8, 2020
0.1.2 Oct 11, 2020

#157 in Procedural macros

Download history 56688/week @ 2024-07-29 59976/week @ 2024-08-05 73425/week @ 2024-08-12 54873/week @ 2024-08-19 67008/week @ 2024-08-26 71547/week @ 2024-09-02 65997/week @ 2024-09-09 63067/week @ 2024-09-16 65904/week @ 2024-09-23 69749/week @ 2024-09-30 71048/week @ 2024-10-07 67677/week @ 2024-10-14 73094/week @ 2024-10-21 61689/week @ 2024-10-28 74594/week @ 2024-11-04 59274/week @ 2024-11-11

271,918 downloads per month
Used in 642 crates (40 directly)

MIT/Apache

54KB
1K SLoC

crates.io docs.rs

derive-syn-parse: A derive macro for syn's Parse trait

This is a fairly straightforward derive macro that produces an implementation syn::parse::Parse for the type it's applied to.

A common pattern when writing custom syn parsers is repeating <name>: input.parse()? for each field in the output. This crate's #[derive(Parse)] handles that for you, with some helpful extra customization.

Usage

Using this crate is as simple as adding it to your 'Cargo.toml' and importing the derive macro:

# Cargo.toml

[dependencies]
derive-syn-parse = "0.2.0"
// your_file.rs
use derive_syn_parse::Parse;

#[derive(Parse)]
struct CustomParsable {
    // ...
}

The derived implementation of Parse will always parse in the order that the fields are given. Detailed information about the various field attributes available is given in the crate documentation.

This crate is primarily intended for users who are already making heavy use of syn and wish to reduce the amount of boilerplate code required.

Motivation

When writing rust code that makes heavy use of syn's parsing functionality, we often end up writing things like:

use syn::parse::{Parse, ParseStream};
use syn::{Ident, Token, Type};

// A simplified struct field
//
//     x: i32
struct MyField {
    ident: Ident,
    colon_token: Token![:],
    ty: Type,
}

impl Parse for MyField {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(MyField {
            ident: input.parse()?,
            colon_token: input.parse()?,
            ty: input.parse()?,
        })
    }
}

This is really repetitive! Ideally, we'd like to just #[derive(Parse)] and have it work. And so we can! (for the most part) Adding #[derive(Parse)] to the previous struct produces an equivalent implementation of Parse:

use syn::{Ident, Token, Type};
use derive_syn_parse::Parse;

#[derive(Parse)]
struct MyField {
    ident: Ident,
    colon_token: Token![:],
    ty: Type,
}

Of course, there are more complicated cases. But - even though they're complicated, many of them are still covered by the various advanced features provided! For more information, see the crate documentation.

Dependencies

~265–720KB
~17K SLoC