#syn #derive

macro syn_derive

Derive macros for syn::Parse and quote::ToTokens

8 releases

0.1.8 Oct 10, 2023
0.1.7 Sep 6, 2023
0.1.6 May 9, 2023
0.1.5 Mar 21, 2023
0.1.2 Nov 14, 2022

#339 in Procedural macros

Download history 6241/week @ 2023-08-05 7414/week @ 2023-08-12 6878/week @ 2023-08-19 7134/week @ 2023-08-26 7954/week @ 2023-09-02 7077/week @ 2023-09-09 8297/week @ 2023-09-16 7250/week @ 2023-09-23 7990/week @ 2023-09-30 8811/week @ 2023-10-07 9564/week @ 2023-10-14 9272/week @ 2023-10-21 11310/week @ 2023-10-28 11333/week @ 2023-11-04 34752/week @ 2023-11-11 47850/week @ 2023-11-18

106,943 downloads per month
Used in 148 crates (4 directly)


302 lines

A simple crate for reducing the boilerplate when writing parsers with syn.


#[derive(Clone, Debug, syn_derive::Parse, syn_derive::ToTokens)]
struct ExampleStruct {
	#[to_tokens(|tokens, val| tokens.append_all(val))]
	attrs: Vec<Attribute>,

	path: Path,

	paren_token: Paren,

	#[syn(in = brace_token)]
	args: Punctuated<Box<Expr>, Token![,]>,

	semi_token: Token![;],

[syn(parenthesized)], [syn(braced)], [syn(bracketed)]: Corresponds to the isonymous macros in syn. Must be attached to Paren, Brace, and Bracket fields, respectively.

#[syn(in = Ident)]: The field is read from inside the named delimiter pair.

#[parse(fn(ParseStream) -> syn::Result<T>)]: A function used to parse the field, often used with Punctuated::parse_terminated or Attribute::parse_outer.

#[to_tokens(fn(&mut TokenStream, &T)]: A function used to tokenize the field. Often used with TokenStreamExt::append_all, though for type resolution reasons this needs to be indirected through a closure expression.


#[derive(Clone, Debug, syn_derive::Parse, syn_derive::ToTokens)]
enum ExampleEnum {
	#[parse(peek = Token![struct])]
	#[parse(peek = Token![enum])]

	Other {
		path: Path,
		semi_token: Token![;],

#[parse(prefix = fn(ParseStream) -> syn::Result<_>)]: A prefix used for all branches, before doing the peeking. Useful when all branches support attributes, for example. The return value is ignored, which gives somewhat suboptimal performance, since the prefix is parsed twice.

#[parse(peek = Token)]: Checks whether the variant should be parsed. Even if multiple peeks succeed, only the first successful variant is attempted.

#[parse(peek_func = fn(ParseStream) -> bool)]: More powerful than peek (such as allowing peek2), but gives worse error messages on failure. peek should be preferred when possible.

Feature flags

  • full (enabled by default): enables syn/full, which is needed to parse complex expressions — such as closures — in attribute values. Without this, you can still use for example paths to functions, but this is much less convenient.


  • derive-syn-parse does not handle ToTokens. It also seems to encourage throwing tokens away with its prefix and postfix attributes.
  • parsel uses its own types for parentheses, meaning the AST types have different API from syn's own.


~19K SLoC