Derive Macro structmeta::ToTokens
source · #[derive(ToTokens)]
{
// Attributes available to this derive:
#[to_tokens]
}
Expand description
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
struct | enum | variant | field | |
---|---|---|---|---|
#[to_tokens("[")] , #[to_tokens("]")] | ✔ | |||
#[to_tokens("(")] , #[to_tokens(")")] | ✔ | |||
#[to_tokens("{")] , #[to_tokens("}")] | ✔ | |||
#[to_tokens(dump)] | ✔ | ✔ |
§#[to_tokens("[", "]", "(", ")", "{", "}"]
By specifying #[to_tokens("[")]
or #[to_tokens("(")]
or #[to_tokens("[")]
, subsequent tokens will be enclosed in []
or ()
or {}
.
By default, all subsequent fields are enclosed.
To restrict the enclosing fields, specify #[to_tokens("]")]
or #[to_tokens(")")]
or #[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);
}
}
If the field type is Bracket
or Paren
or Brace
, the symbol corresponding to the token type must be specified.
If the field type is MacroDelimiter
, any symbol can be used and there is no difference in behavior. (Three types of parentheses are available, no matter which symbol is specified.)
field type | start | end |
---|---|---|
syn::token::Bracket | "[" | "]" |
syn::token::Paren | "(" | ")" |
syn::token::Brace | "{" | "}" |
syn::MacroDelimiter | "[" or "(" or "{" | "]" or ")" or "}" |
§#[to_tokens(dump)]
Causes a compile error and outputs the code generated by #[derive(ToTokens)]
as an error message.