Derive Macro structmeta::ToTokens[][src]

#[derive(ToTokens)]
{
    // Attributes available to this derive:
    #[to_tokens]
}

Derive quote::ToTokens for syntax tree node.

Example

#[derive(ToTokens)] generates an implementation of ToTokens that calls ToTokens::to_tokens for each field.

use syn::LitInt;
 
#[derive(structmeta::ToTokens)]
struct Example(LitInt, LitInt);

Code like this will be generated:

impl quote::ToTokens for Example {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        self.0.to_tokens(tokens);
        self.1.to_tokens(tokens);
    }
}

#[derive(ToTokens)] can also be specified for enum.

use syn::{LitInt, LitStr};
 
#[derive(structmeta::ToTokens)]
enum Example {
    A(LitInt),
    B(LitStr),
}

Code like this will be generated:

impl quote::ToTokens for Example {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            Self::A(l) => l.to_tokens(tokens),
            Self::B(l) => l.to_tokens(tokens),
        }
    }
}

Helper attributes

structenumvaraintfield
#[to_tokens("[")], #[to_tokens("]")]
#[to_tokens("(")], #[to_tokens(")")]
#[to_tokens("{")], #[to_tokens("}")]
#[to_tokens(dump)]

#[to_tokens("[")], #[to_tokens("]")]

By specifying #[to_tokens("[")] for a field of type syn::token::Bracket, subsequent tokens will be enclosed in [].

By default, all subsequent fields are enclosed. To restrict the enclosing fields, specify #[to_tokens("]")] for the field after the end of the enclosure.

use syn::{token, LitInt};
 
#[derive(structmeta::ToTokens)]
struct Example {
    x: LitInt,
    #[to_tokens("[")]
    bracket_token: token::Bracket,
    y: LitInt,
    #[to_tokens("]")]
    z: LitInt,
}

Code like this will be generated:

impl quote::ToTokens for Example {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        self.x.to_tokens(tokens);
        token::Bracket::surround(&self.bracket_token, tokens, |tokens| {
            self.y.to_tokens(tokens);
        });
        self.z.to_tokens(tokens);
    }
}

#[to_tokens("(")], #[to_tokens(")")]

By specifying #[to_tokens("(")] for a field of type syn::token::Paren, subsequent tokens will be enclosed in ().

By default, all subsequent fields are enclosed. To restrict the enclosing fields, specify #[to_tokens(")")] for the field after the end of the enclosure.

#[to_tokens("{")], #[to_tokens("}")]

By specifying #[to_tokens("{")] for a field of type syn::token::Brace, subsequent tokens will be enclosed in {}.

By default, all subsequent fields are enclosed. To restrict the enclosing fields, specify #[to_tokens("}")] for the field after the end of the enclosure.

#[to_tokens(dump)]

Causes a compile error and outputs the code generated by #[derive(ToTokens)] as an error message.